我试图从名为“ Org”的集合中检索文档,并将其存储在列表中以显示在下拉菜单中,但是列表返回[Instance of 'QueryDocumentSnapshot', Instance of 'QueryDocumentSnapshot']
,因此出现以下错误:
The method 'map' was called on null.
Receiver: null
Tried calling: map(Closure: (dynamic) => DropdownMenuItem<dynamic>)
这是我实现的代码:
void organisation() async {
await Firebase.initializeApp();
QuerySnapshot querySnapshot = await FirebaseFirestore.instance.collection("Org").get();
final List<DocumentSnapshot> list = querySnapshot.docs;
print(list);
list.forEach((data) => print(data));
}
@override
initState() {
Firebase.initializeApp();
organisation();
super.initState();
}
这是我实施dropdownmenu的方式:
DropdownButtonFormField(
validator: (value) => value == "Select" ? 'Field required' : null,
value: _selectorg,
onChanged: (val) => setState(() => _selectorg = val),
items: list.map(
(item) {
return DropdownMenuItem(
child: Text('$item'),
value: item,
);
},
).toList(),
hint: Text(
"SELECT ORGANISATION",
style: TextStyle(color: Colors.white)),
),
答案 0 :(得分:1)
尝试一下,
@override
initState() {
super.initState();
Firebase.initializeApp();
organisation();
}
然后
在函数外声明列表
final List<DocumentSnapshot> list;
void organisation() async {
await Firebase.initializeApp();
QuerySnapshot querySnapshot = await FirebaseFirestore.instance.collection("Org").get();
list = querySnapshot.docs;
print(list);
list.forEach((data) => print(data));
}
更新
StreamBuilder(
stream: FirebaseFirestore.instance.collection("Org").get();
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshots) {
if (snapshots.connectionState == ConnectionState.active &&
snapshots.hasData) {
print(snapshots.data);
return ListView.builder(
itemCount: snapshots.docs.length,
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot doc = snapshots.data[index];
Map data= doc.data;//This is your data
return Text(
data.toString(),
);
},
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),