Vinasirajan Vilakshan
Vinasirajan Vilakshan

Reputation: 327

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

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"),);}
}

Upvotes: 1

Views: 3031

Answers (1)

Luis C&#225;rcamo
Luis C&#225;rcamo

Reputation: 348

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.

Upvotes: 1

Related Questions