Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter TextFormField initial value not working

Tags:

flutter

dart

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.

like image 886
TheDizzle Avatar asked Oct 21 '25 15:10

TheDizzle


2 Answers

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.

like image 152
Sami Issa Avatar answered Oct 24 '25 08:10

Sami Issa


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();
        },
      ),
    ],
  ),
),
like image 45
Ketan Ramani Avatar answered Oct 24 '25 10:10

Ketan Ramani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!