Search code examples
flutterdartflutter-getx

The getter 'fromJson' isn't defined for the type in Dart


I am learning flutter, trying to use Getx's GetConnect Custom configuration,

when try to set defaultDecoder for default request, it complains:

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"

How to fix this error?

Here is My Code:

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"]);
  }
}

Solution

  • Check this 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)));
    }
    

    and Then
    httpClient.defaultDecoder = CityModel.listFromJson;