skip to Main Content

I am trying to return a Future<List> in an async function, which is constructed when another Future completes.

Future<List<String>> myFunc() async {
  <Future<List<String>> eventDescriptions;

  googleCalendarApi.events.list('primary').then((events) => {
    eventDescriptions = events.items.map((e) => e.description).toList();
  }

  return eventDescriptions;

I had assumed that the completion of the googleCalendarApi.events.list() would asynchronously create the eventDescriptions such that it would be happy to do the Future assignment (in the Future).

But Flutter complains about the assignment because the result is a List not a Future<List> even though the assignment is done in the future!

2

Answers


  1. Chosen as BEST ANSWER

    So this is my solution to the problem, this does do the right thing now I understand the execution of an async function.

    Future<List<String>> myFunc() async {
        Events events = await googleCalendarApi.events.list('primary',
            timeMin: DateTime.now(), singleEvents: true, orderBy: 'startTime');
    
        return events.items!.map((e) => e.description).whereType<String>().toList();
      }
    

  2. Try this way,

     Future<List<String>> myFunc() async {
          Completer<List<String>> completer = Completer();
        
          googleCalendarApi.events.list('primary').then((events) => {
            List<String> eventDescriptions = events.items.map((e) => e.description).toList();
            completer.complete(eventDescriptions);
          });
        
          return completer.future;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search