Flutter-使用提供程序在init上获取数据的最佳方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter-使用提供程序在init上获取数据的最佳方法相关的知识,希望对你有一定的参考价值。

我想知道什么是在屏幕上获取数据并捕获任何错误以通过对话框显示的最佳方法。

这是我目前的做法。

我的提供者:

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');
    
  

我的主屏幕:

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

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

我希望在初始化时可以使用我的数据,并且还想显示一个对话框,以防万一出错。

谢谢。

答案

尝试像这样使用FutureBuilder

另一答案

太好了,我以为我必须使用Consumer才能从提供者那里显示它。

以上是关于Flutter-使用提供程序在init上获取数据的最佳方法的主要内容,如果未能解决你的问题,请参考以下文章