Flutter Get firebase collection data to list of object

Viewed 583

I have a class name 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,
  });
}

My data is saved in collection name: MyTodos. I want to add a collection in a list like List<Todo> _todo=[Todo...]

1 Answers

I'd advise creating a fromJson factory method to this Todo class, that way mapping the Firebase documents' data to a strongly-typed PODO (Plain Ol' Dart Object) is easier to manipulate in Flutter.

Your updated Todo class would look like:

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']
    );
  }
}

Then, wherever you're pulling the Firebase data from your collection ** MyTodos**, you should do the mapping, as such:

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

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

Then you can do anything you want with your _todos collection. For example, inside a provided service, you can grab the data as follows:

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;
   }
}

Then in your widget's build method you can consume this provider as such:


@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();

       }
    )
 );

}
Related