首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型'Future<List<Appointment>>‘不是类型转换中的类型'List<Appointment>’的子类型

类型'Future<List<Appointment>>‘不是类型转换中的类型'List<Appointment>’的子类型
EN

Stack Overflow用户
提问于 2021-10-21 16:16:02
回答 1查看 54关注 0票数 1

错误应该是清楚的,但我不确定如何避免它。

基本上,我使用getData()方法每秒调用一个流构建器,用新数据更新我的SfCalendar。

代码语言:javascript
复制
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;
}

但是我的约会方法foo()的类型是Future,而不是List。

代码语言:javascript
复制
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;
}

这就是错误应该说明的问题,对吧?我试着从foo()约会中删除Future cast,但是我不能使用async。我也尝试返回Future.value(约会),但同样的错误。

这是我在initState()中调用我的流的地方:

代码语言:javascript
复制
@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");
}, onError: (error) {
  print(error);
});

print("code controller is here");
}

谢谢,请在可能的情况下帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-21 17:22:52

就像JavaScript一样,异步函数总是返回一个未来。这就是当你从返回类型中移除Future时不能使用async的原因。

由于您不是在等待Future解析,因此您实际上是在尝试将Future强制转换为一个列表,这不是有效的强制转换。您所需要做的就是等待函数完成,这样它就会解析为一个列表:

代码语言:javascript
复制
List<Appointment> appointments = await foo() as List<Appointment>;

而且,因为您的返回类型是Future,所以实际上不需要强制转换结果。

代码语言:javascript
复制
List<Appointment> appointments = await foo();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69665450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档