首页 > 解决方案 > 屏幕没有小部件

问题描述

我有一个根据 csv 加载一些小部件的屏幕。但是屏幕只是空了。

Column(
   children: getPlates(),
),
  List<Widget> getPlates() {
    List<Widget> listWidgets = [];
    listWidgets.add(Text('dew'));
    loadAsset('assets/Postres.csv').then((dynamic output) {
      List<String> list = output.split('\n');
      listWidgets.add(Text('holaaaa'));
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
    });
    setState(() {

    });
    return listWidgets;
  }

  Future<String> loadAsset(String path) async {
    return await rootBundle.loadString(path);
  }

我认为这是因为异步方法 loadAsset 在屏幕已经是 bult 时会返回一些东西。我尝试在 initState 中加载它,但只有在我按下热重载时才有效

标签: flutterdart

解决方案


As the assets are loaded asynchronously, they will not be populated in the synchronous getPlates function. You have a couple options here:

  1. Use FutureBuilder. It is a very easy-to-use and powerful widget. This would be the approach I would recommend.
  2. Make your getPlates() function async so you can use the async and await keyword, although I am not sure that is what you are looking for here as I am guessing you reference it from the build method.
  3. Fix your current code; it has a bug. You setState after the then call. The correct approach is wrapping the listWidgets.add inside the setState, like so:
loadAsset('assets/Postres.csv').then((dynamic output) {
// Add the setState here like so
setState(() {
      List<String> list = output.split('\n');
      listWidgets.add(Text('holaaaa'));
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
});
    });

Regardless of what method you pick to fix this--you probably shouldn't start loading the csv in the build method. Consider starting the load in your initState method.


推荐阅读