DropdownButton Value does not update even after selecting different items.
如果默认值为null,则显示错误消息,并且如果我传递任何默认值(不为null),则永远不会更改为其他选定值。
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(),
),
);
}),
帮助我解决此问题。提前致谢。
触发setState将安排新的构建(build
始终在收到调用后调用该方法setState
)。
因此,我建议您将查询移到窗口小部件之外,并在initState
语句中初始化流,这样就不会在每次状态更改时都计算出该流(除非您真正需要它)。
同时将您currentCategory
的widgetbuild
方法移到外部。
这样的事情应该工作:
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;
});
}
)
)
}
)
);
}
}
另请注意,setState
仅适用于有状态的小部件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句