来自 Future 的数据消失了

Data from Future disappears

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

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!

我没有得到什么?

您的错误在 _refresh 函数上。当你处理未来时,在 then 你永远不会将 catList 值分配给 catList (List<Cat>)。一个简单的修复方法是:

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