gpt4 book ai didi

firebase - 类型 '_InternalLinkedHashMap' 不是类型转换中类型 'TodoModel' 的子类型

转载 作者:行者123 更新时间:2023-12-03 04:42:27 29 4
gpt4 key购买 nike

嗨,我是 Flutter 的新手,遇到了问题。
我想将从 Firestore 获取的数据添加到 List 类型的变量中,但出现错误。我花了几个小时来解决这个问题,但效果不佳。
有人知道我是如何得到这个错误的吗?
toto_model.dart

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;
}
todo_provider.dart
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>

最佳答案

你不能在 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);
}
如果您只想授予对变量的读取访问权限,并且它永远不会更改,则可以将其标记为 final 并让公众看到它。这与只为变量创建一个 getter 相同。
Dart 还支持直接指向它应该初始化的类的变量的构造函数参数。再说一次,我们可以这样做以使其更简单。

关于firebase - 类型 '_InternalLinkedHashMap<String, dynamic>' 不是类型转换中类型 'TodoModel' 的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62966315/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com