在MyHomePage状态窗口小部件中,我有一个DropDownButton和一个ListView。我正在尝试根据选定的DropDownMenuItem重建ListView。但是,我在填充ListView时遇到问题。我必须转到另一个视图,然后返回MyHomePage以显示数据。
MyHomePageState:
class _MyHomePageState extends State<MyHomePage> {
final List<String> _dow = [
'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'
].toList();
@override
void initState() {
selectedDow = _dow.first;
super.initState();
}
@override
Widget build(BuildContext context) {
final _dowOptions = _dow.map((String day) =>
new DropdownMenuItem(value: day, child: new Text(day))).toList();
return new Scaffold(
appBar: new AppBar(
title: new DropdownButton(
value: selectedDow, items: _dowOptions, onChanged: (s) {
setState(() {
selectedDow = s;
}
);
}),
actions: <Widget>[
new IconButton(icon: new Icon(Icons.edit), onPressed: () {}),
new IconButton(icon: new Icon(Icons.add), onPressed: () {
newItem();
})
],
),
body: new DisplayList(),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add), onPressed: editItem),
);
}
}
显示列表:
class DisplayList extends StatefulWidget {
DisplayList({Key key}) : super(key: key);
@override
_DisplayListState createState() => new _DisplayListState();
}
class _DisplayListState extends State<DisplayList> {
List<DataModel> dowList = new List<DataModel>();
String currentCollection = selectedDow.toLowerCase();
@override
void initState() {
updateList();
super.initState();
}
updateList() {
Firestore.instance
.collection(currentCollection)
.snapshots
.listen((snapshot) {
for (var doc in snapshot.documents) {
Firestore.instance.collection(doc['colPath'])
.document(doc['docId'])
.get()
.then((docSnap) {
String docId = docSnap.documentID;
String docTitle = docSnap.data['title'];
DataModel wData = new DataModel(
docId, docTitle, null);
dowList.add(wData);
});
}
});
}
@override
Widget build(BuildContext context) {
return new ListView(
children: dowList.map((DataModel item) {
return new ListTile(
title: new Text(item.title),
);
}).toList(),
);
}
}
提前感谢您的任何建议!
答案 0 :(得分:0)
您的听众未通知您StatefulWidget
州已更改。您可以通过将列表修改放入setState
:
setState(() { dowList.add(wData); });
但是,使用StreamBuilder
可能会更好; Firestore提供了一个与其一起使用的流并处理所有更新。所以,无论你通常放置new DisplayList()
,你都会把它放在...... {/ p>
new StreamBuilder(
stream: Firestore.instance.collection(currentCollection).snapshots,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return new Text('Loading...');
return new ListView(
children: [... build your list items here ...],
);
},
);