0

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 Answers3

0

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);
  }
Rohan Jariwala
  • 1,564
  • 2
  • 7
  • 24
0

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

nifesi
  • 80
  • 7
0

You can use then() method since it returns the value from Future

 MyItemProvider({reference}) {
    getUid().then((uid) {
        itemsReference = reference ?? FirebaseFirestore.instance.collection(uid);
    });
  }
Sowat Kheang
  • 668
  • 2
  • 4
  • 12