Home > OS >  shared_preferences values returning null in flutter
shared_preferences values returning null in flutter

Time:07-21

I am using shared_preferences to store a bool value locally but I think I am doing something wrong. So first of all, here is my initState:

  @override
  initState(){
    super.initState();
    checkIfUserHasData();
    getBoolValuesSF();
}

on checkIfUserHasData, Im calling another function at the end (addBoolToSF)

 Future<void> checkIfUserHasData  ()async {
    var collection = FirebaseFirestore.instance.
    collection('users').doc(userID).collection('personalInfo');
    var querySnapshots = await collection.get();
    for (var snapshot in querySnapshots.docs) {
      documentID = snapshot.id;
    }
    await FirebaseFirestore.instance
        .collection('users')
        .doc(userID)
        .collection('personalInfo').doc(documentID)
        .get().then((value) {
      if (!mounted) return;
      setState(()  {
        gender = value.get('gender');
        profileImageUrl = value.get('url');
        print(profileImageUrl);
   
        print(gender);
      });
    });
    if (gender != null){
      if (!mounted) return;
      setState((){
        isUserNew = false;
      });
      if(gender == "Male"){
        setState(() => genderIsMale = true);
        addBoolToSF();



      }else{
        setState(() => genderIsMale = false);
        addBoolToSF();

      }
    }else {
      return;
    }

  }

Then addBoolToSF:

addBoolToSF() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('genderType', genderIsMale);
  }

Lastely getBoolValuesSF:

getBoolValuesSF() async {
   SharedPreferences prefs = await SharedPreferences.getInstance();

   setState(() {
     bool _genderType = ((prefs.getBool('genderType') ?? true)) ;
     genderType = _genderType;
   });
 }

When the genderType value is obtained I then decide which image to be the background image on the screen:

CachedNetworkImage(
            placeholder: (context, url) =>
                CircularProgressIndicator(),
            imageUrl: genderType ? // : //

With all of that said, here is what is happening when the gender is changed on the firebase firestore: The first time I navigate or refresh the screen nothing is changed and I get this error:

type 'Null' is not a subtype of type 'bool'

The second time I refresh or navigate to the screen, I do get the correct image on place but I get the same error message again

type 'Null' is not a subtype of type 'bool'

I have tried several ways to solve this issue but i dont seem to get it right.

Edit: I have noticed that when I removed the last part for CachedNetworkImage, I get no error so I think the problem might be on this part

CodePudding user response:

checkIfUserHasData() and getBoolValuesSF() both are future method. you can create another async method and put it inside initState.

  @override
  initState(){
    super.initState();
    newMthod();
}


newMthod() async{
await checkIfUserHasData();
await getBoolValuesSF();
}

CodePudding user response:

In case like that when you need to wait for a future to build some UI, the go to way is to use a FutureBuilder

You use it like this

FutureBuilder<bool>(
        future: getBoolValuesSF,
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          // build your UI here based on snapshot value
        },
      )
  • Related