flutter - 屏幕没有小部件
问题描述
我有一个根据 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 中加载它,但只有在我按下热重载时才有效
解决方案
As the assets are loaded asynchronously, they will not be populated in the synchronous getPlates
function. You have a couple options here:
- Use FutureBuilder. It is a very easy-to-use and powerful widget. This would be the approach I would recommend.
- Make your
getPlates()
functionasync
so you can use theasync
andawait
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. - Fix your current code; it has a bug. You
setState
after the then call. The correct approach is wrapping thelistWidgets.add
inside thesetState
, 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.
推荐阅读
- heroku - 使用 CloudFront 进行 Azure AD 身份验证
- vue.js - 根据在 Vuejs 中单击的框 div 显示/隐藏 div。检查图像以更好地理解
- docker - Kubernetes/Docker 使用过多的磁盘空间
- python-3.x - Windows 操作系统中的窗口可以超出屏幕多远
- sql - ORACLE 和 SQL Server 中的 MIN 函数工作方式不同
- php - 按值对数组进行排序,同时保留键顺序
- python - 将非常大的 3D Python 列表转换为 numpy 数组永远不会完成
- c# - 使用 Parquet.NET 编写 Parquet 文件适用于本地文件,但会导致 Blob 存储中的文件为空
- javascript - 为什么我不从我的构造函数返回任何东西?
- java - 我正在调用 init 方法失败;嵌套异常是存储库类方法调用上的 java.lang.IllegalArgumentException