Flutter flift onChanged:不触发读取文本字段内容的方法

Flutter flift onChanged:不触发读取文本字段内容的方法,flutter,onchange,Flutter,Onchange,我有一个表单,用户可以在其中捕获多个文本字段的信息。在Onchange:中,我可以看到每当用户在textfield上键入内容时都会有活动。但是,当我调用一个方法来读取textfield内容时,该方法没有被激发。例如,我在nameController文本字段的OnChange:中调用updateFirstName()方法。由于FirstName字段为空,因此当我按Save时,该方法不会启动,应用程序也会失败。下面代码中的updateFirstName方法没有被调用的原因是什么?我是个新手,所以我可

我有一个表单,用户可以在其中捕获多个文本字段的信息。在Onchange:中,我可以看到每当用户在textfield上键入内容时都会有活动。但是,当我调用一个方法来读取textfield内容时,该方法没有被激发。例如,我在nameController文本字段的OnChange:中调用updateFirstName()方法。由于FirstName字段为空,因此当我按Save时,该方法不会启动,应用程序也会失败。下面代码中的updateFirstName方法没有被调用的原因是什么?我是个新手,所以我可能错过了一些基本的东西

import 'dart:ffi';
import 'package:flutter/material.dart';
import '../widgets/main_drawer.dart';
import '../utils/database_helper.dart';
import '../models/customer.dart';
import 'package:intl/intl.dart';

class CustomerDetailsScreen extends StatefulWidget {
  static const routeName = '/customer-details';

  @override
  _CustomerDetailsScreenState createState() => _CustomerDetailsScreenState();
}

class _CustomerDetailsScreenState extends State<CustomerDetailsScreen> {
  //Define editing controllers for all the text fields
  TextEditingController nameController = TextEditingController();
  TextEditingController surnameController = TextEditingController();
  TextEditingController cellphoneController = TextEditingController();
  TextEditingController emailController = TextEditingController();

  //Connecting to the database
  DatabaseHelper helper = DatabaseHelper();

  //Define some variables
  String appBarTitle;
  Customer customer; //This is the Customer Model

  /*
  String sFirstName;
  String sSurname;
  String sCellNumber;
  String sEmailAddress;
  String sCompanyName = '-';
*/

  var _formKey = GlobalKey<FormState>();

  //Method to validate e-mail address
  bool validateEmail(String value) {
    Pattern pattern =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regex = new RegExp(pattern);
    return (!regex.hasMatch(value)) ? false : true;
  }

  @override
  Widget build(BuildContext context) {
    TextStyle textStyle = Theme.of(context).textTheme.title;

    //Populate the text fields
    //nameController.text = customer.sFirstName;
    //surnameController.text = customer.sSurname;
    //cellphoneController.text = customer.sCellNumber;
    //emailController.text = customer.sEmailAddress;

    return Scaffold(
      appBar: AppBar(
        title: Text('Edit Customer'),
      ),
      body: GestureDetector(
        //Gesture detector wrapped the entire body so we can hide keyboard \
        // when user clicks anywhere on the screen
        behavior: HitTestBehavior.opaque,
        onTap: () {
          FocusScope.of(context).requestFocus(new FocusNode());
        },
        child: Form(
          key: _formKey,
          child: Padding(
            padding: EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),
            child: ListView(
              children: <Widget>[
                //First Element - Name
                Padding(
                  padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                  child: TextFormField(
                    controller: nameController,
                    style: textStyle,
                    textCapitalization: TextCapitalization.words,
                    validator: (String value) {
                      if (value.isEmpty) {
                        return 'Please enter your name';
                      }
                      return null;
                    },
                    onChanged: (value) {
                      debugPrint('Something changed on the Name Text Field');

                      updateFirstName();
                    },
                    decoration: InputDecoration(
                      labelText: 'Name',
                      labelStyle: textStyle,
                      errorStyle:
                          TextStyle(color: Colors.redAccent, fontSize: 15.0),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      ),
                    ),
                  ),
                ),

                //Second Element - Surname
                Padding(
                  padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                  child: TextFormField(
                    controller: surnameController,
                    style: textStyle,
                    textCapitalization: TextCapitalization.words,
                    validator: (String value) {
                      if (value.isEmpty) {
                        return 'Please enter your surname';
                      }
                      return null;
                    },
                    onChanged: (value) {
                      debugPrint('Something changed on the Surname Text Field');
                      updateSurname();
                    },
                    decoration: InputDecoration(
                      labelText: 'Surname',
                      labelStyle: textStyle,
                      errorStyle:
                          TextStyle(color: Colors.redAccent, fontSize: 15.0),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      ),
                    ),
                  ),
                ),

                //Third Element - Cellphone
                Padding(
                  padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                  child: TextFormField(
                    controller: cellphoneController,
                    style: textStyle,
                    keyboardType: TextInputType.number,
                    validator: (String value) {
                      if (value.isEmpty) {
                        return 'Please enter your cellphone number';
                      } else {
                        if (value.length < 10)
                          return 'Cell number must be at least 10 digits';
                      }
                      return null;
                    },
                    onChanged: (value) {
                      debugPrint(
                          'Something changed on the Cellphone Text Field');
                      updateCellNumber();
                    },
                    decoration: InputDecoration(
                      labelText: 'Cellphone',
                      labelStyle: textStyle,
                      errorStyle:
                          TextStyle(color: Colors.redAccent, fontSize: 15.0),
                      hintText: 'Enter Cell Number e.g. 0834567891',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      ),
                    ),
                  ),
                ),

                //Fourth Element - Email Address
                Padding(
                  padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                  child: TextFormField(
                    controller: emailController,
                    style: textStyle,
                    keyboardType: TextInputType.emailAddress,
                    validator: (String value) {
                      if (value.isEmpty) {
                        return 'Please enter your e-mail address';
                      } else {
                        //Check if email address is valid.
                        bool validmail = validateEmail(value);
                        if (!validmail) {
                          return 'Please enter a valid e-mail address';
                        }
                      }
                      return null;
                    },
                    onChanged: (value) {
                      debugPrint(
                          'Something changed on the Email Address Text Field');
                      updateEmailAddress();
                    },
                    decoration: InputDecoration(
                      labelText: 'E-mail',
                      labelStyle: textStyle,
                      errorStyle:
                          TextStyle(color: Colors.redAccent, fontSize: 15.0),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      ),
                    ),
                  ),
                ),

                //Fifth Element - Row for Save Button
                Padding(
                    padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: RaisedButton(
                              color: Theme.of(context).primaryColorDark,
                              textColor: Theme.of(context).primaryColorLight,
                              child: Text(
                                'Save',
                                textScaleFactor: 1.5,
                              ),
                              onPressed: () {
                                setState(() {
                                  if (_formKey.currentState.validate()) {
                                    debugPrint('Save button clicked');

                                    //Call the Save method only if the validation is passed
                                    _saveCustomerDetails();
                                  }
                                });
                              }),
                        ),
                      ],
                    )),
              ],
            ),
          ),
        ),
      ),
    );
  }

  //**********************Updating what is captured by the user on each text field******************/

  //Update the sFirstName of the Customer model object
  void updateFirstName() {
    print('The updateFirstName was called');

    customer.sFirstName = nameController.text;
  }

  //Update the sSurname of the Customer model object
  void updateSurname() {
    customer.sSurname = surnameController.text;
  }

  //Update the sCellNumber of the Customer model object
  void updateCellNumber() {
    customer.sCellNumber = cellphoneController.text;
  }

  //Update the sEmailAddress of the Customer model object
  void updateEmailAddress() {
    customer.sEmailAddress = emailController.text;
    customer.sCompanyName = '-';
  }

  //**********************END - Updating what is captured by the user on each text field******************/

  //**************************Saving to the Database*************************************/

  void _saveCustomerDetails() async {
    //moveToLastScreen();

    //Update the dtUpdated of the Customer model with current time (Confirm that it is GMT)

    print('Trying to save customer info was called');

    customer.dtUpdated = DateFormat.yMMMd().format(DateTime.now());

    print('Trying to save customer info was called - 2');

    int result;

    result = await helper.insertNewHumanCustomer(customer);

    if (result != 0) {
      //Saving was a Success
      _showAlertDialog('Success', 'Customer details saved successfully');

      print('The customer details were saved successfully');
    } else {
      //Saving was a Failure

      print('FAILURE - The customer details failed to save');

      _showAlertDialog('Failure', 'Oopsy.....something went wrong. Try again');
    }
  }

  //*****Show Alert Popup message*****/
  void _showAlertDialog(String title, String message) {
    AlertDialog alertDialog = AlertDialog(
      title: Text(title),
      content: Text(message),
    );

    showDialog(context: context, builder: (_) => alertDialog);
  }
//*****END - Show Alert Popup message*****/

  //**************************Saving to the Database*************************************/

}
导入'dart:ffi';
进口“包装:颤振/材料.省道”;
导入“../widgets/main_drawer.dart”;
导入“../utils/database_helper.dart”;
导入“../models/customer.dart”;
导入“包:intl/intl.dart”;
类CustomerDetailsScreen扩展StatefulWidget{
静态常量routeName='/customer details';
@凌驾
_CustomerDetailsScreenState createState()=>\u CustomerDetailsScreenState();
}
类_CustomerDetailsScreenState扩展状态{
//为所有文本字段定义编辑控制器
TextEditingController name控制器=TextEditingController();
TextEditingController=TextEditingController();
TextEditingController cellphoneController=TextEditingController();
TextEditingController emailController=TextEditingController();
//连接到数据库
DatabaseHelper=DatabaseHelper();
//定义一些变量
字符串appBarTitle;
Customer;//这是客户模型
/*
字符串sFirstName;
字符串序列名称;
字符串sCellNumber;
字符串语义地址;
字符串sCompanyName='-';
*/
var_formKey=GlobalKey();
//验证电子邮件地址的方法
bool validateEmail(字符串值){
图案=
r'^([^()[\]\\,;:\s@']+(\.[^()[\]\,;:\s@']+*))(\[[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[1,3}.[0-9]{1,3}.]124;([a-zA Z-0-9]{a-zA Z]++$){2};
RegExp regex=新的RegExp(模式);
返回(!regex.hasMatch(value))?false:true;
}
@凌驾
小部件构建(构建上下文){
TextStyle TextStyle=Theme.of(context).textTheme.title;
//填充文本字段
//nameController.text=customer.sFirstName;
//name controller.text=customer.sSurname;
//cellphoneController.text=customer.sCellNumber;
//emailController.text=customer.sEmailAddress;
返回脚手架(
appBar:appBar(
标题:文本(“编辑客户”),
),
正文:手势检测器(
//手势检测器包裹了整个身体,所以我们可以隐藏键盘\
//当用户单击屏幕上的任意位置时
行为:HitTestBehavior.不透明,
onTap:(){
FocusScope.of(context).requestFocus(newfocusnode());
},
孩子:表格(
键:_formKey,
孩子:填充(
填充:仅限边缘设置(顶部:15.0,左侧:10.0,右侧:10.0),
子:ListView(
儿童:[
//第一个元素-名称
填充物(
填充:仅限边缘设置(顶部:15.0,底部:15.0),
子项:TextFormField(
控制器:名称控制器,
风格:textStyle,
textcapitalize:textcapitalize.words,
验证器:(字符串值){
if(value.isEmpty){
返回“请输入您的姓名”;
}
返回null;
},
一旦更改:(值){
debugPrint(“名称文本字段中的某些内容已更改”);
updateFirstName();
},
装饰:输入装饰(
labelText:'名称',
标签样式:文本样式,
错误样式:
TextStyle(颜色:Colors.redAccent,字体大小:15.0),
边框:大纲输入边框(
边界半径:边界半径。圆形(5.0),
),
),
),
),
//第二要素——姓氏
填充物(
填充:仅限边缘设置(顶部:15.0,底部:15.0),
子项:TextFormField(
控制员:控制员,,
风格:textStyle,
textcapitalize:textcapitalize.words,
验证器:(字符串值){
if(value.isEmpty){
返回“请输入您的姓氏”;
}
返回null;
},
一旦更改:(值){
debugPrint(“姓氏文本字段中的某些内容发生了更改”);
updateSurname();
},
装饰:输入装饰(
labelText:“姓氏”,
标签样式:文本样式,
错误样式:
TextStyle(颜色:Colors.redAccent,字体大小:15.0),
边框:大纲输入边框(
边界半径:边界半径。圆形(5.0),
),
),
),
),
//第三要素——手机
填充物(
填充:仅限边缘设置(顶部:15.0,底部:15.0),
子项:TextFormField(
控制器:手机控制器,
风格:textStyle,
键盘类型:TextInputType.number,
验证器:(字符串值){
if(value.isEmpty){
返回“请输入您的手机号码”;
}否则{