list - Flutter 获取 firebase 集合数据到对象列表

标签 list flutter class object addition

我有一个类(class)名称 Todo

class TodoField {
  static const createdTime = 'createdTime';
}

class Todo {
  DateTime createdTime;
  String title;
  String id;
  String description;
  bool isDone;

  Todo({
    @required this.createdTime,
    @required this.title,
    this.description = '',
    this.id,
    this.isDone = false,
  });
}

我的数据保存在集合名称中:MyTodos。我想在像 List<Todo> _todo=[Todo...] 这样的列表中添加一个集合

最佳答案

我建议为这个 Todo 类创建一个 fromJson 工厂方法,这样可以将 Firebase 文档的数据映射到强类型 PODO(Plain Ol' Dart) Object)在 Flutter 中更容易操作。

更新后的 Todo 类将如下所示:

class Todo {
  DateTime createdTime;
  String title;
  String id;
  String description;
  bool isDone;

  Todo({
    @required this.createdTime,
    @required this.title,
    this.description = '',
    this.id,
    this.isDone = false,
  });

  factory Todo.fromJson(Map<String, dynamic> json) {
    return Todo(
       createdTime: json['createdTime'],
       title: json['title'],
       id: json['id'],
       description: json['description'],
       isDone: json['isDone']
    );
  }
}

然后,无论您从集合 ** MyTodos** 中提取 Firebase 数据,您都应该进行映射,如下所示:

QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('MyTodos').get();

List<Todo> _todos = snapshot.docs.map((d) => Todo.fromJson(d.data())).toList();

然后您就可以对您的 _todos 收藏做任何您想做的事情。例如,在提供的服务中,您可以按如下方式获取数据:

class TodosProvider extends ChangeNotifier {

   Future<List<Todo>> GetData() async {
       QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('MyTodos').get(); 
       List<Todo> _todos = snapshot.docs.map((d) => Todo.fromJson(d.data())).toList();
       return _todos;
   }
}

然后在您的小部件的build方法中,您可以这样使用此提供程序:


@override
Widget build(BuildContext context) {
 
 // obtain the provided service
 // make sure this service is injected at the root via 
 // either a ChangeNotifierProvider or MultiProvider
 var todos = Provider.of<TodosProvider>(context, listen: false);

 return Scaffold(
    body: FutureBuilder(
       future: todos.GetData(),
       builder: (context, snapshot) {

         if (snapshot.hasData) {
            // here consume your Todos
            List<Todo> todos = snapshot.data as List<Todo>;

            // put them in a list or whatever you want
         }

         return CircularProgressIndicator();

       }
    )
 );

}

关于list - Flutter 获取 firebase 集合数据到对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71375595/

相关文章:

python - numpy 数组列表格式

java - if 语句表现不同

flutter - 制作 GridView ,元素之间没有间隙

ios - 将 Flutter 模块暴露为 IOS 框架会导致 "Failed to find assets path for "Frameworks/App.framework/flutter_assets"

java - 执行Java程序时出错: Could not find or load main class

python - 根据字符串拆分将列表拆分为子列表

java - 在 JAVA 的列表中追加一个方法

android - 打开应用程序后 flutter 崩溃

c++ - 使用类的成员

c++ - set<> 类,当我插入类时,它不接受我的 < 运算符