期望类型为 'Map<String, dynamic>' 的值,但得到的类型为“() => Map<String, dynamic>?”
Expected a value of type 'Map<String, dynamic>', but got one of type '() => Map<String, dynamic>?'
我正在使用 Firebase cloud firestore 开发带有 flutter 的网络应用程序。
我想从 firestore 获取值,但是出现错误,无法获取。
错误;
Expected a value of type 'Map<String, dynamic>', but got one of type '() => Map<String, dynamic>?'
代码;
Future<String> getData(String collection, String field) async {
DocumentSnapshot docSnapshot =
await FirebaseFirestore.instance.collection(collection).doc().get();
Map<String, dynamic> record = docSnapshot.data as Map<String, dynamic>;
return record[field];
}
FutureBuilder(
future: getData("users", "userName"),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const SizedBox(
width: 50,
child: LinearProgressIndicator(),
);
}
if (snapshot.hasError) {
return SelectableText(snapshot.error.toString());
}
if (!snapshot.hasData) {
return const Text('No data found');
}
return Text('${snapshot.data}');
},
)
这段代码是调用getData()
的FutureBuilder,发生错误时在屏幕上显示错误语句。
经过一番研究,我找到了一种消除错误的方法。这样的代码;
Map<String,dynamic> record = new Map<String,dynamic>.from(docSnapshot.data["songs"]);
但是,这在语法上是不正确的,会导致编译错误。
从 2019 年到现在,Firestore 似乎发生了很大变化,是这个原因吗?
docSnapshot.data["songs"]
这对 DocumentSnapshot
无效。
谁能解决这个错误?谢谢。
加法 1;
我更改了代码,但出现了其他类似的错误。
第一个错误已解决。
Map<String, dynamic> record = docSnapshot.data() as Map<String, dynamic>;
Expected a value of type 'Map<String, dynamic>', but got one of type
'Null'
Firestore 确认数据“用户名”正确存在。
我相信 DocumentSnapshot.data
是一种方法,因此您应该将其更改为:DocumentSnapshot.data()
我正在使用 Firebase cloud firestore 开发带有 flutter 的网络应用程序。
我想从 firestore 获取值,但是出现错误,无法获取。
错误;
Expected a value of type 'Map<String, dynamic>', but got one of type '() => Map<String, dynamic>?'
代码;
Future<String> getData(String collection, String field) async {
DocumentSnapshot docSnapshot =
await FirebaseFirestore.instance.collection(collection).doc().get();
Map<String, dynamic> record = docSnapshot.data as Map<String, dynamic>;
return record[field];
}
FutureBuilder(
future: getData("users", "userName"),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const SizedBox(
width: 50,
child: LinearProgressIndicator(),
);
}
if (snapshot.hasError) {
return SelectableText(snapshot.error.toString());
}
if (!snapshot.hasData) {
return const Text('No data found');
}
return Text('${snapshot.data}');
},
)
这段代码是调用getData()
的FutureBuilder,发生错误时在屏幕上显示错误语句。
经过一番研究,我找到了一种消除错误的方法。这样的代码;
Map<String,dynamic> record = new Map<String,dynamic>.from(docSnapshot.data["songs"]);
但是,这在语法上是不正确的,会导致编译错误。 从 2019 年到现在,Firestore 似乎发生了很大变化,是这个原因吗?
docSnapshot.data["songs"]
这对 DocumentSnapshot
无效。
谁能解决这个错误?谢谢。
加法 1;
我更改了代码,但出现了其他类似的错误。 第一个错误已解决。
Map<String, dynamic> record = docSnapshot.data() as Map<String, dynamic>;
Expected a value of type 'Map<String, dynamic>', but got one of type 'Null'
Firestore 确认数据“用户名”正确存在。
我相信 DocumentSnapshot.data
是一种方法,因此您应该将其更改为:DocumentSnapshot.data()