0

I'm getting an

'await' can only be used in 'async' or 'async*' methods.

In popup error:

The await expression can only be used in an async function. Try marking the function body with either 'async' or 'async*'.dart(await_in_wrong_context)

firestore.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:workout/main.dart';

class FirestoreViewModel {
  Future<List<int>> getDocuments(
      String type, int numValues, bool isDescending) async {
    List<int> _list;
    QuerySnapshot documents = await FirebaseFirestore.instance
        .collection('workouts')
        .where('id', isEqualTo: googleSignIn.currentUser.id)
        .orderBy('date', descending: isDescending)
        .limit(numValues)
        .get();

    _list = documents.docs.map((snapshot) => snapshot['water'] as int).toList();
    return _list;
  }
}

file.dart

import 'package:workout/services/firestore_view_model.dart';

List<int> _waters = await FirestoreViewModel().getDocuments("water", 7, true);

I just can't seem to get a list with all the Futures, awaits, and asyncs going around. I've looked at other solutions on here but they are set up a bit differently. Either way, I don't know how to create a method that returns a list, when the firestore is full of futures. Any ideas would be appreciated.

tazboy
  • 1,685
  • 5
  • 23
  • 39
  • 1
    Pay attention to what file and line number the error refers to. It's surely not to your code in `firestore.dart`, and if it's the code you posted from `file.dart`, you didn't provide enough context. If you have trouble understanding `Future`s, perhaps see [What is a Future and how do I use it?](https://stackoverflow.com/q/63017280/). If you have a `List` of `Future`s, you'll need to `await` each of them. – jamesdlin Jan 10 '21 at 01:11
  • Updated to show the entirety of code of both files. await is being underlined in file.dart. Thoughts? The popup says "await_in_wrong_context". Does that mean anything? – tazboy Jan 10 '21 at 01:28
  • 1
    You can't use `await` to initialize a global variable. As explained, `await` can be used only in an `async` method/function. You can make `_waters` a *getter*, however: `Future> get _waters async => await FirestoreViewModel().getDocuments("water", 7, true);`. Note that that also must return a `Future`. – jamesdlin Jan 10 '21 at 02:40

0 Answers0