rozerro
rozerro

Reputation: 7216

What to use instead of await in initState() method?

I get this error

A value of type 'Future' can't be assigned to a variable of type 'double'. because we can not use assync in initState() method.

class _SettingsState extends State<Settings> {
  bool _isSwitched = false;
  double _sliderValue = 0;

  @override
  void initState() async {
    _sliderValue = _getInterval();
    super.initState();
  }
...

Future<double> _getInterval() async { ...

But if we will try to use await in the initState() then we'll get the message

Rather than awaiting on asynchronous work directly inside of initState, call a separate method to do this work without awaiting it.

How can I use _getInterval inside initState, i.e. recieve a future value from it, without awaiting it?

Upvotes: 0

Views: 553

Answers (2)

Pieter van Loon
Pieter van Loon

Reputation: 5648

Just call the _getInterval method without awaiting it and change it to instead of returning the value assign it to the _sliderValue at the end of the method (probably also calling setState)

Upvotes: 1

Abbas Jafari
Abbas Jafari

Reputation: 1641

If you want to run this code _sliderValue = _getInterval();, you can put it inside a seperate method

void myMethod() async{
   _sliderValue = await _getInterval();
}

And then call it inside initState method, like below:

@override
  void initState() async {
    super.initState();
    myMethod();
  }

Upvotes: 1

Related Questions