不断收到此错误:'package:flutter / src / widgets / text.dart':失败的断言:第241行pos 10:'data!= null'

时间:2019-07-31 18:09:35

标签: flutter dart

对不起,大量的代码!我只是从入门开始,对整个编程来说还是一个新手。我试图制作一个可正常运行的可提交表单,并按照教程进行操作,但是在尝试加载表单页面时,我总是收到此错误:

'package:flutter / src / widgets / text.dart':失败的断言:第241行pos 10:'data!= null'

我已经附加了代码,但是如果这是错误的代码,请告诉我,我可以附加其他lib文件。当它起作用时,我希望它可以以可提交的形式提交到我拥有的并以JSON编码的URL。 非常感谢您的帮助!

我尝试删除所有验证,并且尝试浏览“ null”,但不确定哪个错误引发错误。

class MyFormPage extends StatefulWidget {
  MyFormPage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _FormPage createState() => new _FormPage();
}

class _FormPage extends State<MyFormPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new 
GlobalKey<ScaffoldState>();
  Contact newContact = new Contact();
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  List<String> _information = <String>[
    '',
    'male',
    'female',
  ];
  String _info = '';

  final TextEditingController _controller = new TextEditingController();
  Future _chooseDate(BuildContext context, String initialDateString) async {
    var now = new DateTime.now();
    var initialDate = convertToDate(initialDateString) ?? now;
    initialDate = (initialDate.year >= 1900 && initialDate.isBefore(now)
        ? initialDate
        : now);

    var result = await showDatePicker(
        context: context,
        initialDate: initialDate,
        firstDate: new DateTime(1900),
        lastDate: new DateTime.now());

    if (result == null) return;

    setState(() {
      _controller.text = new DateFormat.yMd().format(result);
    });
  }

  DateTime convertToDate(String input) {
    try {
      var d = new DateFormat.yMd().parseStrict(input);
      return d;
    } catch (e) {
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new SafeArea(
          top: false,
          bottom: false,
          child: new Form(
              key: _formKey,
              autovalidate: true,
              child: new ListView(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                children: <Widget>[
                  new TextFormField(
                    decoration: const InputDecoration(
                      icon: const Icon(Icons.person),
                      hintText: 'Enter your first name',
                  labelText: 'First Name',
                ),
                inputFormatters: [new LengthLimitingTextInputFormatter(15)],
                validator: (val) =>
                    val.isEmpty ? 'First name is required' : null,
                onSaved: (val) => newContact.firstName = val,
              ),
              new TextFormField(
                decoration: const InputDecoration(
                  icon: const Icon(Icons.person),
                  hintText: 'Enter your last name',
                  labelText: 'Last Name',
                ),
                inputFormatters: [new LengthLimitingTextInputFormatter(15)],
                validator: (val) =>
                    val.isEmpty ? 'Last name is required' : null,
                onSaved: (val) => newContact.lastName = val,
              ),
              new Row(children: <Widget>[
                new Expanded(
                    child: new TextFormField(
                  decoration: new InputDecoration(
                    icon: const Icon(Icons.calendar_today),
                    hintText: 'Enter your date of birth',
                    labelText: 'D.O.B.',
                  ),
                  controller: _controller,
                  keyboardType: TextInputType.datetime,
                  onSaved: (val) => newContact.dob = convertToDate(val),
                )),
                new IconButton(
                  icon: new Icon(Icons.more_horiz),
                  tooltip: 'Choose date',
                  onPressed: (() {
                    _chooseDate(context, _controller.text);
                  }),
                )
              ]),
              new TextFormField(
                decoration: const InputDecoration(
                  icon: const Icon(Icons.phone),
                  hintText: 'Enter a phone number',
                  labelText: 'Phone',
                ),
                keyboardType: TextInputType.phone,
                inputFormatters: [
                  new WhitelistingTextInputFormatter(
                      new RegExp(r'^[()\d -]{1,15}$')),
                ],
                validator: (value) => isValidPhoneNumber(value)
                    ? null
                    : 'Phone number must be entered as (###)###-####',
                onSaved: (val) => newContact.phone = val,
              ),
              new TextFormField(
                decoration: const InputDecoration(
                  icon: const Icon(Icons.email),
                  hintText: 'Enter a email address',
                  labelText: 'Email',
                ),
                keyboardType: TextInputType.emailAddress,
                validator: (value) => isValidEmail(value)
                    ? null
                    : 'Please enter a valid email address',
                onSaved: (val) => newContact.email = val,
              ),
              new FormField(
                builder: (FormFieldState<String> state) {
                  return InputDecorator(
                    decoration: InputDecoration(
                      icon: const Icon(Icons.group),
                      labelText: 'Gender',
                      errorText: state.hasError ? state.errorText : null,
                    ),
                    isEmpty: _info == '',
                    child: new DropdownButtonHideUnderline(
                      child: new DropdownButton<String>(
                        value: _info,
                        isDense: true,
                        onChanged: (String newValue) {
                          setState(() {
                            newContact.gender = newValue;
                            _info = newValue;
                            state.didChange(newValue);
                          });
                        },
                        items: _information.map((String value) {
                          return new DropdownMenuItem<String>(
                            value: value,
                            child: new Text(value),
                          );
                        }).toList(),
                      ),
                    ),
                  );
                },
                validator: (val) {
                  return val != '' ? null : 'Please select a gender';
                },
              ),
              new Container(
                  padding: const EdgeInsets.only(left: 40.0, top: 20.0),
                  child: new RaisedButton(
                    child: const Text('Submit'),
                    onPressed: _submitForm,
                  )),
            ],
          ))),
    );
  }

  bool isValidPhoneNumber(String input) {
    final RegExp regex = new RegExp(r'^\(\d\d\d\)\d\d\d\-\d\d\d\d$');
    return regex.hasMatch(input);
  }

 bool isValidEmail(String input) {
    final RegExp regex = new RegExp(
        r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)*$");
    return regex.hasMatch(input);
  }

  bool isValidDob(String dob) {
    if (dob.isEmpty) return true;
    var d = convertToDate(dob);
    return d != null && d.isBefore(new DateTime.now());
  }

  void showMessage(String message, [MaterialColor color = Colors.red]) {
    _scaffoldKey.currentState.showSnackBar(
        new SnackBar(backgroundColor: color, content: new Text(message)));
  }

  void _submitForm() {
    final FormState form = _formKey.currentState;

    if (!form.validate()) {
      showMessage('Form is not valid!  Please review and correct.');
    } else {
      form.save(); //This invokes each onSaved event

      print('Form save called, newContact is now up to date...');
      print('First Name: ${newContact.firstName}');
      print('Last Name: ${newContact.lastName}');
      print('Dob: ${newContact.dob}');
      print('Phone: ${newContact.phone}');
      print('Email: ${newContact.email}');
      print('Gender: ${newContact.gender}');
      print('========================================');
      print('Submitting to back end...');
      var contactService = new ContactService();
      contactService.createContact(newContact).then((value) => showMessage(
          'New contact created for ${value.firstName}!', Colors.blue));
    }
  }
}

因此,当我单击该按钮导航到表单页面时,出现红色屏幕,显示我上面提到的错误代码。如果它可以正常工作,则会显示一个注册页面。

1 个答案:

答案 0 :(得分:0)

您的标题可能为空,这在转到文本小部件时会导致此错误。您可以如下添加默认标题:

MyFormPage({Key key, this.title = ''}) : super(key: key);