所以我試圖從firestore表中傳遞一個字串值串列,但我遇到了一個例外type 'Future<dynamic>' is not a subtype of type 'List<dynamic>'
這是功能
getLectureList(String userId) async {
var collection = FirebaseFirestore.instance.collection('students');
var docSnapshot = await collection.doc(userId).get();
Map<String, dynamic>? data = docSnapshot.data();
List<String> _lectureList =
await data!['attendance']; //This line is kinda giving me trouble
userInfo = FirestoreWrapper()
.getStudentFromData(docId: currentUser(), rawData: data);
return _lectureList;
}
這是我拋出例外的函式
@override
void initState() {
lectureList = getLectureList(currentUser()); // Getting an exception here
NearbyConn(context).searchDevices(devices: deviceList);
super.initState();
}
嘗試在getLectureList()方法中使用 await 但仍然遇到同樣的問題
uj5u.com熱心網友回復:
你為什么要做你await的資料?你已經明白了。
List<String> _lectureList = data!['attendance'];
請注意,我不知道你的資料結構是什么樣的,所以我不能告訴你這是否正確,我只能告訴你它比以前更正確,因為await不屬于那里。
uj5u.com熱心網友回復:
您在這里遇到例外,lectureList = getLectureList(currentUser());因為該getLectureList()方法所需的引數是 userId,它是一個字串。我不知道currentUser()回傳什么,但我假設它是呼叫該getLectureList()方法時需要的 userId。根據錯誤,它看起來像是currentUser()一個異步方法,它在一段時間后回傳未來。
你不是在等待那個未來。您不應該使initState()方法異步,因此將代碼塊從其中移出到單獨的方法中,然后從initState().
像這樣的東西,
@override
void initState() {
super.initState();
_getData();
}
void _getData() async {
lectureList =
getLectureList(await currentUser());
NearbyConn(context).searchDevices(devices: deviceList);
}
要么
@override
void initState() {
super.initState();
_getData();
}
void _getData() async {
String _userID = await currentUser();
lectureList = getLectureList(_userID);
NearbyConn(context).searchDevices(devices: deviceList);
}
我推薦,這樣你就可以看到所有的部分。
使您的方法引數成為必需的命名引數還可以幫助您輕松查看傳遞給函式/類/所需的內容。
例如。
getLectureList({required String userId}){
...
}
您的 IDE 會提醒您該函式所需的物件型別,這會使事情變得更清晰。
最終,我認為鍵入您的類可以更容易地從 fireStore鍵入 CollectionReference 和 DocumentReference獲取資料
這樣你就可以輕松做到這一點,
final moviesRef = FirebaseFirestore.instance.collection('movies').withConverter<Movie>(
fromFirestore: (snapshot, _) => Movie.fromJson(snapshot.data()!),
toFirestore: (movie, _) => movie.toJson(),
);
并以這種方式獲取您的資料,
Future<void> main() async {
// Obtain science-fiction movies
List<QueryDocumentSnapshot<Movie>> movies = await moviesRef
.where('genre', isEqualTo: 'Sci-fi')
.get()
.then((snapshot) => snapshot.docs);
// Add a movie
await moviesRef.add(
Movie(
title: 'Star Wars: A New Hope (Episode IV)',
genre: 'Sci-fi'
),
);
// Get a movie with the id 42
Movie movie42 = await moviesRef.doc('42').get().then((snapshot) => snapshot.data()!);
}
保持一切干燥整潔。
uj5u.com熱心網友回復:
< The data comes to list format thats why showing the exception of datatype >
List<String> lectureList = await getLectureList(currentUser()); // use
Future<List<String>> getLectureList(String userId) async {
- your code -
}
uj5u.com熱心網友回復:
而不是 List _lectureList = await data!['attendance'];
試試這個 _lectureList = await data![] As List
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442461.html
