Home > OS >  How to return boolean based on firestore value
How to return boolean based on firestore value

Time:10-03

I have a boolean value in firestore, i need to set a condition based on this boolean. I am trying to get this boolean from firestore and then using it in my futurebuilder but i am always getting null even if i can see values are there in firestore. Please help.

 Future<bool> getUser() async {
 dynamic data;
 bool isUser=false;

final DocumentReference document =   
 FirebaseFirestore.instance.collection('users').doc(uida).collection('pre').doc();

isUser = await document.get().then<dynamic>(( DocumentSnapshot snapshot) async{
  data =snapshot.data;
  final data1 = data.map((doc) => doc['enrolled']);
  print(data1.toString());
  if (data1==true){
   setState(() {
     isUser = true;
    });}
  });

return isUser;
 }

Widget

    return FutureBuilder(
    future: getUser(),
    builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
   
      if (snapshot.data == true)
     
        return Text(snapshot.data.toString());

CodePudding user response:

You can use the code below it will solve your issue, but check two things do you have all required permissions to fetch data from firebase and also check if the document id is correct ? you can use use if(snapshot.data!.exists) to check if the document exist in the current collection

   import 'package:cloud_firestore/cloud_firestore.dart';
   import 'package:firebase_auth/firebase_auth.dart';
    import 'package:flutter/material.dart';

  class TestClass extends StatefulWidget {
   const TestClass({Key? key}) : super(key: key);

   @override
     _TestClassState createState() => _TestClassState();
     }

      class _TestClassState extends State<TestClass> {
     final _auth = FirebaseAuth.instance;
     final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
      @override
      Widget build(BuildContext context) {
     return Scaffold(
     body: FutureBuilder<DocumentSnapshot>(
      future: _fireStore
          .collection('users').doc(uida).collection('pre').doc(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Center(child: Text(snapshot.data!['enrolled'].toString()));
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      }),
       );
     }
    }

CodePudding user response:

When using asynchronous code, it is better to either use async and await or use then. In your case async and await will give a more readable code.

For your getUser function this would be something like:

 Future<bool> getUser() async {
 dynamic data;
 bool isUser=false;

 final DocumentReference document =   
  FirebaseFirestore.instance.collection('users').doc(uida).collection('pre').doc();

isUser = await document.get()
data = snapshot.data;
final data1 = data['enrolled'];
print(data1.toString());
if (data1==true){
   setState(() {
     isUser = true;
    });}
  });

return data1;
}

And for the Futurebuilder, it is better to check whether the snapshot contains data, by using snapshot.hasData like this:

return FutureBuilder(
future: getUser(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {

  if (snapshot.hasData)
    if (snapshot.data ==true){
 
       return Text(snapshot.data.toString());
    } else {
       return Text('still waiting for data...')

See https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html for a much better explanation.

  • Related