Home > OS >  type 'Future<List<Appointment>>' is not a subtype of type 'List<Appoin
type 'Future<List<Appointment>>' is not a subtype of type 'List<Appoin

Time:10-22

The error should be clear but I'm unsure how to go around it.

Basically I have a Stream builder I'm calling every second by getData() method to update my SfCalendar with new data.

Stream<DataSource> getData() async* {
  await Future.delayed(const Duration(seconds: 1)); //Mock delay
  List<Appointment> appointments = foo() as List<Appointment>;
  List<CalendarResource> resources = bar() as List<CalendarResource>;
  DataSource data = DataSource(appointments, resources);
  print("Fetched Data");
  yield data;
}

But my appointments method foo() is of type Future<List> and not List.

Future<List<Appointment>> foo() async {
  var url0 = Uri.https(
      "uri",
      "/profiles.json");
  List<Appointment> appointments = [];
  try {
    final response = await dio.get(url0.toString());

    //final Random random = Random();
    //_colorCollection[random.nextInt(9)];
    response.data.forEach((key, value) {
      appointments.add(
        Appointment(
          id: int.parse(
            value["id"],
          ),
          startTime: DateTime.parse(value["startTime"]),
          endTime: DateTime.parse(value["endTime"]),
        ),
      );
    });
  } catch (error) {
    print(error);
  }
  return appointments;
}

That is what the error should be telling, yes? I tried removing the Future cast from foo() appointments but then I can't use async. I also tried returning Future.value(appointments) but same error.

This is where I call my Stream in initState():

@override
void initState() {
super.initState();

print("Creating a sample stream...");
Stream<DataSource> stream = getData();
print("Created the stream");

stream.listen((data) {
  print("DataReceived");
}, onDone: () {
  print("Task Done");
}, one rror: (error) {
  print(error);
});

print("code controller is here");
}

Thank you, please help when possible

CodePudding user response:

Just like JavaScript, async functions always return a Future. That's why you can't use async when you remove Future from the return type.

Since you're not waiting for that Future to resolve, you're actually trying to cast a Future to a List, which isn't a valid cast. All you should need to do is wait for the function to finish so it resolves to a List:

List<Appointment> appointments = await foo() as List<Appointment>;

and, since your return type is Future<List<Appointment>>, you don't actually need to cast the result.

List<Appointment> appointments = await foo();
  • Related