嗨,我是Flutter的新手,遇到了问题。 我想将从Firestore提取的数据添加到List类型的变量中,但出现错误。我花了几个小时来解决这个问题,但效果不佳。
有人知道我怎么得到这个错误吗?
class TodoModel {
String _title = '';
bool _done = false;
int _id = 1;
String _docId = '';
TodoModel(String title, bool done, int id, String docId) {
this._title = title;
this._done = done;
this._id = id;
this._docId = docId;
}
String get title => _title;
bool get done => _done;
int get id => _id;
String get docId => _docId;
}
class TodoProvider {
List<TodoModel> _todoList = [];
Future<List<TodoModel>> fetchToDo() async {
final result = await Firestore.instance.collection('todos').getDocuments();
final List<DocumentSnapshot> documents = result.documents;
documents.forEach((document) {
var data = {
'title': document.data['title'],
'done': document.data['done'],
'id': document.data['id'],
'docId': document.documentID,
};
_todoList.add(data as TodoModel);
});
return _todoList;
}
}
E/flutter ( 5859): [ERROR:flutter/shell/common/shell.cc(199)] Dart Error: Unhandled exception:
E/flutter ( 5859): type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'TodoModel' in type cast
E/flutter ( 5859): #0 TodoProvider.fetchToDo.<anonymous closure> (package:flutterbloc/resources/todo_provider.dart:21:26)
E/flutter ( 5859): #1 List.forEach (dart:core-patch/growable_array.dart:285:8)
E/flutter ( 5859): #2 TodoProvider.fetchToDo (package:flutterbloc/resources/todo_provider.dart:13:15)
E/flutter ( 5859): <asynchronous suspension>
答案 0 :(得分:1)
您不能在Dart中创建一个Map,然后将其投射到给定的对象中。您需要调用要从中获取给定对象的类的构造函数。因此,在您情况下应该是:
_todoList.add(TodoModel(
document.data['title'] as String,
document.data['done'] as bool,
document.data['id'] as int,
document.documentID as String));
我还想补充一点,您当前的TodoModel
类可以简化为:
class TodoModel {
final String title;
final bool done;
final int id;
final String docId;
TodoModel(this.title, this.done, this.id, this.docId);
}
如果您只想授予对变量的读取权限,并且它永远不会改变,则可以将其标记为最终值,并让公众看到。就像只为该变量做一个吸气剂一样。
Dart还支持构造函数参数,该参数直接指向应初始化的类的变量。同样,我们可以这样做使其更简单。