【问题标题】:Data from Future disappears未来的数据消失了
【发布时间】:2020-03-12 21:25:00
【问题描述】:

我需要从 API 获取数据并将其放入 ListView。它通过按下 FloatingActionButton 调用“_refresh()”方法来实现。它收到 10 只猫并将其放入列表中。 在这个方法中,我调用了另一个方法“_builtListView()”,它应该创建一个 ListView 元素及其 Cat 行,但似乎猫在另一个方法中消失了,尽管它发生在一个类中。

class _MyHomePageState extends State<MyHomePage> {

  var catList = new List<Cat>();

  void _refresh() {
    var catsFuture = fetchCats();
    catsFuture.then((catList) {
      print("Future cats catch: " + catList.length.toString() + " cats.");
      _builtListView();
    });
    setState(() { });
  }

  Future<List<Cat>> fetchCats() async {
    // getting cats code
    print("fetchCats(): " + catListFetched.length.toString() + " cats.");
    return catListFetched;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _builtListView(),
      floatingActionButton: FloatingActionButton(
        onPressed: _refresh,
        tooltip: 'Refresh',
        child: Icon(Icons.refresh),
      ),
    );
  }

  Widget _builtListView() {
    if (catList.isEmpty)
      print("_builtListView, catList is empty!");
    return ListView.builder(
      itemCount: catList == null ? 0 : catList.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text("Text " + index.toString()),  //catList[index].toString()),
        );
      },
    );
  }
}

我在控制台看到了什么:

I/flutter (10172): _builtListView, catList is empty!
//_refresh
I/flutter (10172): _builtListView, catList is empty!
I/flutter (10172): fetchCats(): 10 cats.
I/flutter (10172): Future cats catch: 10 cats.
I/flutter (10172): _builtListView, catList is empty!

我没有得到什么?

【问题讨论】:

    标签: android flutter dart future


    【解决方案1】:

    您的错误在于_refresh 函数。当您处理未来时,在then,您永远不会将catList 值分配给catList (List&lt;Cat&gt;)。一个简单的解决方法是:

    void _refresh() {
        var catsFuture = fetchCats();
        catsFuture.then((_catListResult) {
          catList = _catListResult;
          print("Future cats catch: " + catList.length.toString() + " cats.");
          _builtListView();
        });
        setState(() { });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-26
      • 2020-10-06
      • 2019-01-22
      • 2020-12-06
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多