Ket*_*ogi 6 flutter google-cloud-firestore dropdownbutton stream-builder
DropdownButton Value does not update even after selecting different items.
Run Code Online (Sandbox Code Playgroud)
如果默认值为空,则显示错误消息,如果我传递任何默认值(非空),则它永远不会更改为其他选定值。
currentCategory 设置为 DropdownButton 的默认值。
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('categories')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
currentCategory = snapshot.data.documents[0];
return DropdownButtonHideUnderline(
child:
new DropdownButtonFormField<DocumentSnapshot>(
value: currentCategory,
onChanged: (DocumentSnapshot newValue) {
setState(() {
currentCategory = newValue;
});
print(currentCategory.data['name']);
},
onSaved: (DocumentSnapshot newValue) {
setState(() {
currentCategory = newValue;
});
},
items: snapshot.data.documents
.map((DocumentSnapshot document) {
return new DropdownMenuItem<DocumentSnapshot>(
value: document,
child: Text(
document.data['name'],
),
);
}).toList(),
),
);
}),
Run Code Online (Sandbox Code Playgroud)
帮助我解决这个问题。提前致谢。
触发setState将安排一个新的构建(该build方法总是在收到对 的调用后调用setState)。
因此,我建议您将查询移到小部件之外,并在语句中初始化流initState,以便每次状态更改时都不会计算它(除非您确实需要它)。
还将您的currentCategory小部件build方法移到外部。
像这样的东西应该有效:
class YourClass extends StatefulWidget {
...
}
class _YourClassState extends State<YourClass> {
Stream<QuerySnapshot> _categories;
DocumentSnapshot _currentCategory;
initState() {
_categories = Firestore.instance.collection('categories').snapshots();
return super.initState();
}
Widget build(BuildContext context) {
return Container(
child: StreamBuilder<QuerySnapshot>(
stream: _categories,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
return DropdownButtonHideUnderline(
child: new DropdownButtonFormField<DocumentSnapshot>(
value: _currentCategory,
onChanged: (DocumentSnapshot newValue) {
setState(() {
_currentCategory = newValue;
});
}
)
)
}
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,setState仅适用于有状态小部件。