【问题标题】:Error: Expected a value of type 'String', but got one of type 'Null'错误:需要一个“字符串”类型的值,但得到一个“空”类型的值
【发布时间】:2021-12-31 14:51:49
【问题描述】:

我在 Flutter 中学习 api 和 http 请求,但在发出 get 请求时出错 我得到了这个错误:错误:期望一个'String'类型的值,但得到一个'Null'类型的值

enter image description here

我收到了这个错误:

enter image description here

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: json flutter flutter-http dart-http


【解决方案1】:

例如,当您将 data[id] 说成 String 时,这意味着:data[id] 为空。

  factory Formule.fromMap(Map? data) {
    if (data == null) {
      return const Formule(
          id: '', title: '', prix: 0, nombreDePlace: 0, alertThreshold: 0, remainingPlaces: 0);
    }
    return Formule(
        id: data['id'] as String,
        title: data['title'] as String,
        prix: data['prix'] as double,
        nombreDePlace: data['nombreDePlace'] as int,
        alertThreshold: data['alertThreshold'] as int,
        remainingPlaces: data['remainingPlaces'] as int);
  }

2 个解决方案:

id: data['id'] as String?,

或者

id: data['id'] as String? ?? "",

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2022-01-08
    • 2021-12-17
    • 2021-09-13
    • 2021-12-04
    • 2021-09-18
    相关资源
    最近更新 更多