skip to Main Content

I’m using flutter and I am trying to get a value from shared_preferences for firebase.

i checked my cord doesn’t work and uid was " Instance of ‘Future’ ".

the solution i found was using setState but i can’t use that because it’s not in Widget build.

in this situation, how can i get value(uid) instead of Instance of ‘Future’

class MyItemProvider with ChangeNotifier {
  String uid = '';
  Future<void> getUid() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    uid = await prefs.getString('uid')!;
  }
  late CollectionReference itemsReference;
  List<Item> items = [];
  List<Item> find_result = [];

  MyItemProvider({reference}) {
    getUid();
    itemsReference = reference ?? FirebaseFirestore.instance.collection(uid);
  }

...
...
...


i try to use setState
i checked ‘print(uid);’ was Instance of ‘Future’

3

Answers


  1. You have to do following things

    String uid = '';
      Future<String> getUid() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        return await prefs.getString('uid')!;
      }
      late CollectionReference itemsReference;
      List<Item> items = [];
      List<Item> find_result = [];
    
      MyItemProvider({reference}) async {
        uid = await getUid();
        debugPrint('userId $uid');
        itemsReference = reference ?? FirebaseFirestore.instance.collection(uid);
      }
    
    Login or Signup to reply.
  2. You need to await your Futute function "getUid" since it is a type of Future where it is being called.

    But you can further your knowledge in dart asynchronous programming, read this

    Login or Signup to reply.
  3. You can use then() method since it returns the value from Future

     MyItemProvider({reference}) {
        getUid().then((uid) {
            itemsReference = reference ?? FirebaseFirestore.instance.collection(uid);
        });
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search