[英]How to update ListView in Flutter
I am a beginner in flutter
, and I want to update my listview
when i load all files in mandarin
directory.我是flutter
的初学者,我想在加载mandarin
目录中的所有文件时更新我的listview
。 I am sure i have got all files and added them to tests
, but i have no ideas what's wrong with my code, why listview
doesn't display anything.我确定我已经获得了所有文件并将它们添加到tests
中,但我不知道我的代码有什么问题,为什么listview
不显示任何内容。 Any ideas?有任何想法吗?
class _TeachersState extends State<TeachersList> {
final _biggerFont = const TextStyle(fontSize: 18.0);
List tests = List();
Widget _buildSuggestions(BuildContext context) {
initTests();
return ListView.builder(
itemCount: tests.length,
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if (i.isOdd) return Divider();
return _buildRow(tests[i]);
});
}
void gotoTest(String title) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => TestList(title)));
}
Widget _buildRow(String pair) {
return ListTile(
onTap: () => gotoTest(pair),
title: Text(
pair,
style: _biggerFont,
),
);
}
void initTests() async {
List t = List();
String baseDir = await ExtStorage.getExternalStorageDirectory();
String waDir = "$baseDir/mandarin";
Directory dir = new Directory(waDir);
dir.list().forEach((element) {
t.add(element.path);
});
setState(() {
tests.addAll(t);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("请选择老师")),
body: _buildSuggestions(context),
);
}
}
Have you tried using the FutureBuilder
widget?您是否尝试过使用FutureBuilder
小部件?
Check the code below:检查下面的代码:
Pass a snapshot to your buildSuggestion method将快照传递给您的 buildSuggestion 方法
Widget _buildSuggestions(BuildContext context, AsyncSnapShot snapshot) {
initTests();
return ListView.builder(
itemCount: snapshot.data.length,
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if (i.isOdd) return Divider();
return _buildRow(snapshot.data[i]);
});
}
Change the function return type更改 function 返回类型
Future initTests() async {
List t = List();
String baseDir = await ExtStorage.getExternalStorageDirectory();
String waDir = "$baseDir/mandarin";
Directory dir = new Directory(waDir);
dir.list().forEach((element) {
t.add(element.path);
});
setState(() {
tests.addAll(t);
});
return tests;
}
Use a future builder widget in your body:在您的身体中使用未来的构建器小部件:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("请选择老师")),
body: FutureBuilder(
future: initTests(),
builder: (context, snapshot){
if (snapshot.hasData){
return _buildSuggestions(context, snapshot);
} else {
return CircularProgressIndicator();
}
},
);
);
}
It will show a Circle Progress Indicator until all the files have been read and then display them when done.它将显示一个圆形进度指示器,直到所有文件都被读取,然后在完成后显示它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.