Reputation: 1574
I am trying to set an initial value if one is created on my text form field. When I run my code:
final apiField = TextFormField(
controller: apiFieldController,
initialValue: _read().toString(),
obscureText: true,
style: style,
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
hintText: "API Key",
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
);
_read() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
String stringValue = prefs.getString('apiKey') ?? '';
return stringValue;
}
I get the following error:
package:flutter/src/material/text_form_field.dart: failed assertion. initial value == null || controller == null is not true
I'm unsure where I'm stuck at. I do see the controller being initialized. I believe my _read() method has an issue, but it does return a string.
Upvotes: 4
Views: 13183
Reputation: 91
You can either establish the initialValue in the TextFormField:
TextFormField(
initialValue: "Initial String",
OR you can establish it with the TextEditingController:
TextEditingController(text:"Initial String");
But you can't do both, that will result in a field assertion error:
Failed assertion: line 196 pos 15: 'initialValue == null || controller == null': is not true.
I prefer to set the controller with an initial value in initState of the widget holding the form.
Upvotes: 1
Reputation: 5753
var _formKey = GlobalKey<FormState>();
Map<String, String> map = {
'Name': '',
};
Inside Widget build(BuildContext context)
Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
key: map['Name'].isEmpty
? Key('Name')
: Key(map['Name']),
initialValue: map['Name'],
onSaved: (value) {
map['Name'] = value.trim();
},
),
],
),
),
Upvotes: 1
Reputation: 1974
Maybe because you set a controller and an initial value. You have to set only one of these properties. Or an initial value or a controller.
Upvotes: 8
Reputation: 2104
Your read()
return Future<string>
instead of string.
You need to set initial value
directly to controller with setState
method
Also I recommend to install static analyses to your project to avoid such issues https://dart.dev/guides/language/analysis-options
Upvotes: 0