简体   繁体   中英

Flutter - Best approach to fetch data on init using provider

I would like to know what's the best approach to fetch the data on a screen and also catch any error to show it with a dialog.

This is my current approach at the moment.

My provider:

Future<People> fetchPeople() async {
    final response = await http.get(url);

    if (response.statusCode == 200) {
      return People.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed loading people');
    }
  }

My home screen:

_fetchData() async {
    try {
      await Provider.of<PeopleModel>(context).fetchPeople();
    } catch (err) {
      // Show dialog
      print(err);
    }
  }

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

I want to have my data available to use on init and also I want to show a dialog just in case there is an error.

Thank you.

Try using FutureBuilder like this

return FutureBuilder(
  future: Future.delayed(Duration(seconds: 2)), // here you provide your future. In your case Provider.of<PeopleModel>(context).fetchPeople()
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator();
    }
    if (snapshot.hasError) {
      return Text('ERROR');
    }
    // DATA is in snapshot.data
    return Text('SUCCESS');
  }
);

There you can handle the loading part, the error and success

If you want your future to run once. You could save it in a variable in initState() and provide that variable to the FutureBuilder

I believe the best approach is using a post frame callback.

  _fetchData() async {
    try {
      await Provider.of<PeopleModel>(context).fetchPeople();
    } catch (err) {
      // Show dialog
      print(err);
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _fetchData();
    });
  }

This article explain this: https://www.didierboelens.com/2019/04/addpostframecallback/

Check the documentation: https://api.flutter.dev/flutter/scheduler/SchedulerBinding/addPostFrameCallback.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM