how to use FutureBuilder with Visibility in a widget flutter

Issue

It has been days since I am trying to figure out how to keep hidden posts hidden from the user, who has hidden it. I tried filtering with .where(), but then i was stuck in figuring how to filter it with the userId, which was NOT in the array in the firestore posts collection. Then I tried setting rules to

match /reviews/{review}{
allow read: if request.auth != null && !(request.auth.uid in 
resource.data.hidingUserId)}
 

but that did not work as well. Was not getting any posts, as permission was denied completely.

So now I am trying following methods:

hidePost(BuildContext context) async {
setState(() {
  isVisible = !isVisible;
});

await postRef.doc(widget.post.postId).update({'hidingUserId': 
FieldValue.arrayUnion([FirebaseAuth.instance.currentUser.uid])});
showInSnackBar(context, Languages.of(context).postHidden);

final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setBool("visibility", !isVisible);
}

getVisibility() async{
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool("visibility");
}

and then in my widget I have:

child: Visibility(
  visible: getVisibility(),
  child: Container(
        decoration: BoxDecoration(
          color: Colors.white60,
          borderRadius: BorderRadius.circular(15.0),
        ),
        child: Column( blahblablah...)

The error I am getting is type 'Future<dynamic>' is not a subtype of type 'bool' on the getVisibility() method. Maybe I need to use FutureBuilder, but I don’t know where to use it. Please, help me get over with this issue? Thank you so much!

Solution

This is how you would use FutureBuilder in this case:

child: FutureBuilder<bool?>(
  future: getVisibility(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting)
      // Return a widget to be used while the data
      // is being loaded from the SharedPreferences
      return Center(child: CircularProgressIndicator());

    final bool? visibility = snapshot.data ?? false;
    return Visibility(
      visible: visibility,
      child: Container(...),
    );
  }
)

Off-topic, but declare your return types explicitly to avoid debugging problems in the future (no pun intended):

Future<bool?> getVisibility() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getBool("visibility");
}

Answered By – enzo

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *