-1

I would like to set an initial value to a form field. I am reading in this answer that it can be done like so

TextEditingController _controller = TextEditingController(text: 'initial value');

But I would like to get the initial value from shared preferences, which is async.

How would I do this?

I tried setting the controller value in initial state but that doesn't work

user3808307
  • 2,270
  • 9
  • 45
  • 99

1 Answers1

1

You have two way :

1 ) get text from prefs BEFORE navigate - or construct widget -. So you can get final variable.

2 ) Load text after initState

class Foo extends StatefulWidget {
 @override
  _FooState createState() {
    return _FooState();
  }
}

class _FooState extends State<Foo> {
  TextEditingController _controller;

  //For check text loaded. bool textLoaded;
  bool textLoaded;

  String text;

  @override
  void initState() {
    textLoaded = false;
    super.initState();
  }

  Future<void> setText() async {
    setState(() {
      text = "GET TEXT FROM PREF";
      _controller = TextEditingController(text: text);
      textLoaded = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        textLoaded
            ? TextField(
                controller: _controller,
              )
            : const CircularProgressIndicator(),
        RaisedButton(
          onPressed: () {
            _controller.clear();
          },
          child: const Text('CLEAR'),
        ),
      ],
    );
  }
}
Mehmet Yaz
  • 195
  • 3