【问题标题】:The getter 'fromJson' isn't defined for the type in Dart没有为 Dart 中的类型定义 getter 'fromJson'
【发布时间】:2021-10-06 04:37:17
【问题描述】:

我正在学习flutter,尝试使用Getx的GetConnectCustom configuration

当尝试为默认请求设置 defaultDecoder 时,它会报错:

The getter 'fromJson' isn't defined for the type 'Resp'.
Try importing the library that defines 'fromJson', correcting the name to the name of an existing getter, or defining a getter or field named 'fromJson'.dart"

如何解决这个错误?

这是我的代码:

import 'package:get/get.dart';

class AuthService extends GetConnect {
  @override
  void onInit() {
    // All request will pass to jsonEncode so CasesModel.fromJson()

    httpClient.defaultDecoder = Resp.fromJson;
    httpClient.baseUrl = 'http://localhost/app_api/auth';

   
  }

  Future<Response<Map<String, dynamic>>> getCaptcha(String mobile) =>
      get("get_captcha");
}

class Resp {
  final int Errcode;
  final String Errmsg;
  final Map<String, dynamic> Data;

  Resp(this.Errcode, this.Errmsg, this.Data);

  factory Resp.fromJson(Map<String, dynamic> json) {
    return Resp(json["errcode"], json["errmsg"], json["data"]);
  }
}

【问题讨论】:

  • 通过添加解决 httpClient.defaultDecoder = (json) => Resp.fromJson(json);

标签: flutter dart flutter-getx


【解决方案1】:

检查这个 https://gist.github.com/eduardoflorence/d918d05ad71175b52c2aca95588c305d

class CityModel {
  CityModel({
    required this.abbreviation,
    required this.name,
  });

  String abbreviation;
  String name;

  factory CityModel.fromJson(Map<String, dynamic> json) => CityModel(
        abbreviation: json["sigla"],
        name: json["nome"],
      );

  static List<CityModel> listFromJson(list) => List<CityModel>.from(list.map((x) => CityModel.fromJson(x)));
}

然后
httpClient.defaultDecoder = CityModel.listFromJson;

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 2021-11-22
    • 1970-01-01
    • 2021-07-27
    • 2020-09-02
    • 2021-07-23
    • 2022-10-09
    • 2021-10-19
    • 2021-08-29
    相关资源
    最近更新 更多