Flutter how to use Future return value as if variable

Issue

I want to get Future return value and use it like variable.
I have this Future function

  Future<User> _fetchUserInfo(String id) async {
    User fetchedUser;
    await Firestore.instance
        .collection('user')
        .document(id)
        .get()
        .then((snapshot) {
      final User user = User(snapshot);
      fetchedUser = user;
    });
    return fetchedUser;
  }

And I want get value like so

final user = _fetchUserInfo(id);

However when I tried to use like this

new Text(user.userName);

Dart doesn’t recognize as User class. It says dynamic.
How Can I get return value and use it?
Am I doing wrong way first of all?
Any help is appreciated!

Solution

You can simplify the code:

Future<User> _fetchUserInfo(String id) async {
    User fetchedUser;
    var snapshot = await Firestore.instance
        .collection('user')
        .document(id)
        .get();
    return User(snapshot);
  }

you also need async/await to get the value

void foo() async {
  final user = await _fetchUserInfo(id);
}

Answered By – Günter Zöchbauer

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.