Reputation: 25
Sorry for the large amount of code! I just started with flutter and am very new to programming as a whole. I am trying to make a functioning submittable form and followed a tutorial to do so, but I keep getting this error when I try to load the form page:
'package:flutter/src/widgets/text.dart': Failed assertion: line 241 pos 10: 'data != null'
I have attached the code, but if this is the wrong bit of code for the error let me know and I can attach the other lib files. When it works, I want this to be submittable form to a URL I have and JSON encoded. I greatly appreciate any help!
I have tried removing all validation, and I have tried looking through the "null(s)", but am unsure which one one is throwing the error.
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));
}
}
}
So, when I click the button to navigate to my form page I get the red screen showing the error code I have mentioned above. If it were to work correctly, a sign-up page should appear.
Upvotes: 2
Views: 6914
Reputation: 619
Your title maybe null, which when it goes to the Text widget would cause this error. You can add a default title as follows:
MyFormPage({Key key, this.title = ''}) : super(key: key);
Upvotes: 5