Flutter how to use Future return value as if variable


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
        .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!


You can simplify the code:

Future<User> _fetchUserInfo(String id) async {
    User fetchedUser;
    var snapshot = await Firestore.instance
    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. Required fields are marked *