0

Just after new page is created, I need to load webservice data (while loading is in progress, busy inducator should be displayed), then when loading done, show data.

My approach is load data inside initState override, this way:

void initState() {
    
      setState(() => _isLoading = true);
      fetchData().then((value) {

       // Do something with data
       widget.value = value;

        setState(() => _isLoading = false);
      });
    }

    super.initState();
  }

Then, build method will display either loading indicator, or loaded data depend from _isLoading value.

For now, it works but I don't feel it's good way, especially afaik, setState call should be avoided inside initState.

Can you provide any tips how to do the same better, without complicating code too much? Or, my approach is acceptable in this case?

1 Answer 1

2

Why don't you use FutureBuilder to build the Widgets?
You'll then be able to deal with the 'loading' state too.

Example:

return FutureBuilder(
    future: yourAsyncCall,
    builder: (context, snapshot) {
      if (!snapshot.hasData) return MaybeProgressBar();
      else return TheWidgetYouMade();
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

FutureBuilder is correct but make sure that yourAsyncCall is made in the initState method, store the result in the state and pass it to the FutureBuilder. Read the docs carefully
Good solution, I forgot about FutureBuilder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.