How can I use flutter provider to get data from Firestore?

1,353

Instead of creating a FutureProvider of DocumentSnaphot, a good solution would be to create a class that wraps the DocumentSnapshot. For example:

class MyClass {
   MyClass(){}

   Future<DocumentSnapshot> getData() async {
      return await FirebaseFirestore.instance.collection("User").doc("xxxx").get();
  }

}

And in the provider declaration you might set something like

 ...
 Provider(create: (_) => MyClass())
 ...

This wouldn't require you to set the initial data.

However, for your case and what it seems that you are trying to do, using an StreamProvider would be better.

For more examples and details on this, I recommend checking out the following websites. You'll find more useful information there.

Share:
1,353
Vinasirajan Vilakshan
Author by

Vinasirajan Vilakshan

Updated on December 13, 2022

Comments

  • Vinasirajan Vilakshan
    Vinasirajan Vilakshan over 1 year

    I used here Future Provider to get data from firestore But it's not allowing me to set the initial Data to null??? It ask me to input a type of . How can I use future Provider to get data from firestore.

    class MyHomePage extends StatelessWidget {
      final _auth = FirebaseAuth.instance;
      
    
      @override
      Widget build(BuildContext context) {
        return FutureProvider<DocumentSnapshot>(create: (_)async{
        return FirebaseFirestore.instance.collection("User").doc("xxxx").get();}, initialData: ,child: Welcome,)
    }}
    
    Widget Welcome (BuildContext context){
    final document = Provider.of<DocumentSnapshot>(context).data;
    if(document==null){
    return Container(
    child: Text("Loading"),);}
    }
    
    • Salih Can
      Salih Can almost 3 years
      You must fill the mandatory parameters of FutureProvider.