【问题标题】:type 'List<dynamic>' is not a subtype of type 'FutureOr<String>''List<dynamic>' 类型不是 'FutureOr<String>' 类型的子类型
【发布时间】:2020-11-26 15:24:20
【问题描述】:

我正在尝试从 Future 类型中检索数据,但我遇到了这个异常:

Exception: type 'List<dynamic>' is not a subtype of type 'FutureOr<String>'

这是返回 Future 的方法:

 class  EtablissementController{

  Future<String> AfficherEtablissement() async {
    final response =
    await http.get('http://10.0.2.2:8080/api/getetab');
    if (response.statusCode == 200) {
      return json.decode(response.body);
    } else {
      throw Exception('Failed to load');
    }
  }
}

我在这里调用这个方法并填充返回的数据:

    etabController = EtablissementController() ;
    //fetching data
  etabController.AfficherEtablissement().then((value) => {
    print("Fetched values: "+value)
  }) ;
    //fetching data

【问题讨论】:

  • 顺便说一句,关于方法名称linkDO name other identifiers using lowerCamelCase.

标签: flutter dart


【解决方案1】:

问题是你通过这个返回不同类型的数据

// this is a json decoded data, not String
return json.decode(response.body);

并提到了在您的通用数据类型中为您的未来返回数据类型字符串

Future<String> AfficherEtablissement() async {}

尝试为您的方法 AfficherEtablissement() 声明正确的数据类型。

建议:使用您的方法名称作为camelCase。良好的飞镖练习,您可以在此处阅读有关飞镖指南的更多信息:Effective Dart

  // return the dynamic data type
  Future<dynamic> AfficherEtablissement() async {
    final response =
    await http.get('http://10.0.2.2:8080/api/getetab');
    if (response.statusCode == 200) {
      return json.decode(response.body);
    } else {
      throw Exception('Failed to load');
    }
  }

而当你获取数据或打印数据时,你必须将其更改为String,通过toString(),因为你得到的是动态数据类型,但在打印时,它需要String

etabController.AfficherEtablissement().then((value) => {
  print("Fetched values: "+value.toString());
});

【讨论】:

  • 感谢您的回答,我刚刚尝试了您建议的方法,但仍然遇到同样的异常
  • 现在您在执行此操作时一定会遇到错误:print("Fetched values: "+value)。尝试这样做print("Fetched values: "+value.toString())。休息会一样,让我知道@CoderTn
  • 谢谢先生!所有最好的@CoderTn :)
【解决方案2】:

不知道你会得到什么回应,但你可以typecast

 Future<String> AfficherEtablissement() async {
    final response =
    await http.get('http://10.0.2.2:8080/api/getetab');
    if (response.statusCode == 200) {
      return json.decode(response.body) as String; // it should return String response. 
    } else {
      throw Exception('Failed to load');
    }
  }

【讨论】:

  • @CoderTn:真正的问题是什么,它是否返回字符串?
猜你喜欢
  • 2021-01-13
  • 2022-07-21
  • 2021-07-14
  • 2022-11-02
  • 2021-08-02
  • 2021-10-15
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多