Flutter NoSuchMethodError: The method '[]' was called on null. how to solve this error when giving get in an api using flutter

Flutter NoSuchMethodError: The method '[]' was called on null. how to solve this error when giving get in an api using flutter

我在通过 get 方法使用 api 时遇到问题。显然错误出在我的模型映射中,但至少对我来说模型没问题。如果有人能帮助我,我将不胜感激。

这是我的方法,我正在使用 get connect 访问 api。 _restClient 指的是我的基础 url.

class ActionPageRepositoryImpl implements ActionPageRepository {
  final RestClient _restClient;

  ActionPageRepositoryImpl({required RestClient restClient})
      : _restClient = restClient;

  @override
  Future<ActionPageModel> getActionPageJobs(int id) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    final String token = sharedPreferences.getString("token") ?? "";

    final Response result =
        await _restClient.get<ActionPageModel>("/job_acoes/$id", headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token'
    }, decoder: (data) {
      if (data != null) {
        print("status codeData ${data}");
        return ActionPageModel.fromMap(data);
      }
      return ActionPageModel.fromMap(data);
    });
    if (result.hasError) {
      print("status codeError ${result.statusCode}");
      throw ("erro ao buscar dados");
    }

    print("status codeBody ${result.body}");
    print("Status codeSucess ${result.statusCode}");

    return result.body ?? "";
  }
}

这是我在这个 get 方法中打印的数据,显然他没有给我 api 的完整 json 反馈,但为什么呢?

status codeData {codigo_cupom: null, data_acao: 2021-07-26, deleted_at: null, descricao: Um Story, hashtags: null, hora_final_acao: 12:00:00, hora_inicial_acao: 08:00:00, job: {canal_entrada: E-Mail, cliente: {cidade: Portland, cliente_id: 1, cnpj: 12.345.678/0001-12, deleted_at: null, descricao: Nike, endereco: 1 Nike Drive, estado: SP, last_modified_by: null, last_time: 2021-07-11T19:13:54+00:00, login_instagram: nike, nome: Nike, nota_fiscal: null, numero_seguidores_instagram: null, observacoes: null, razao_social: Nike Inc, telefone_comercial: (11) 1111-1111, website: https://nike.com}, cliente_id: 1, data_inicio: 2021-07-24, deleted_at: null, descricao: Mais um teste, influenciador: {altura: null, avatar: pessoas/21/avatar.png, busto_cms: null, calcinha_sunga_tamanho: null, casting_mailing: null, cidade: null, cidade_nascimento: null, cintura_cms: null, cnpj: 27179660000138, cor_cabelo: null, cor_olhos: null, cpf: 048.677.923-81, dados_bancarios_agencia: 1322, dados_bancarios_banco: 12, dados_bancarios_

这是我的模型

class ActionPageModel {
  String influencerNome;
  String sobreNome;
  String descricaoJob;
  String nome;
  String dataDoJob;
  String horarioDoJob;
  String briefing;
  String site;
  String hashTag;
  String cupom;
  ActionPageModel({
    required this.influencerNome,
    required this.sobreNome,
    required this.descricaoJob,
    required this.nome,
    required this.dataDoJob,
    required this.horarioDoJob,
    required this.briefing,
    required this.site,
    required this.hashTag,
    required this.cupom,
  });
  

  Map<String, dynamic> toMap() {
    return {
      'influencerNome': influencerNome,
      'sobreNome': sobreNome,
      'descricaoJob': descricaoJob,
      'nome': nome,
      'dataDoJob': dataDoJob,
      'horarioDoJob': horarioDoJob,
      'briefing': briefing,
      'site': site,
      'hashTag': hashTag,
      'cupom': cupom,
    };
  }

  factory ActionPageModel.fromMap(Map<String, dynamic> map) {
    return ActionPageModel(
      influencerNome: map["influenciador"]["nome"],
      sobreNome: map['influenciador']["sobrenome"],
      descricaoJob: map['job']["cliente"]["descricao"] ?? "",
      nome: map['job']["cliente"]['nome'] ?? "",
      dataDoJob: map['data_acao'] ?? "",
      horarioDoJob: map['hora_inicial_acao'] ?? "",
      briefing: map['descricao'] ?? "", //!FICAR DE OLHO NESSE CAMPO,
      site: map['job']["cliente"]["website"] ?? "",
      hashTag: map['hashtags'] ?? "",
      cupom: map['codigo_cupom'] ?? "",
    );
  }

  String toJson() => json.encode(toMap());

  factory ActionPageModel.fromJson(String source) => ActionPageModel.fromMap(json.decode(source));
}

这是json,它很长但是我用这个标记了我需要获取数据的区域

{
    "codigo_cupom": null, //THIS
    "data_acao": "2021-07-26", //THIS
    "deleted_at": null,
    "descricao": "Um Story",
    "hashtags": null,
    "hora_final_acao": "12:00:00",
    "hora_inicial_acao": "08:00:00", //THIS
    "job": {
        "canal_entrada": "E-Mail",
        "cliente": {
            "cidade": "Portland",
            "cliente_id": 1,
            "cnpj": "12.345.678/0001-12",
            "deleted_at": null,
            "descricao": "Nike", //THIS
            "endereco": "1 Nike Drive",
            "estado": "SP",
            "last_modified_by": null,
            "last_time": "2021-07-11T19:13:54+00:00",
            "login_instagram": "nike",
            "nome": "Nike", //THIS
            "nota_fiscal": null,
            "numero_seguidores_instagram": null,
            "observacoes": null,
            "razao_social": "Nike Inc",
            "telefone_comercial": "(11) 1111-1111",
            "website": "https://nike.com" //THIS
        },
        "cliente_id": 1,
        "data_inicio": "2021-07-24",
        "deleted_at": null,
        "descricao": "Mais um teste",
        "influenciador": {
            "altura": null,
            "avatar": "pessoas/21/avatar.png",
            "busto_cms": null,
            "calcinha_sunga_tamanho": null,
            "casting_mailing": null,
            "cidade": null,
            "cidade_nascimento": null,
            "cintura_cms": null,
            "cnpj": "27179660000138",
            "cor_cabelo": null,
            "cor_olhos": null,
            "cpf": "048.677.923-81",
            "dados_bancarios_agencia": 1322,
            "dados_bancarios_banco": 12,
            "dados_bancarios_conta": "0283614-9",
            "dados_bancarios_pf_chave_pix": null,
            "dados_bancarios_pf_cpf": null,
            "dados_bancarios_pf_nome": null,
            "dados_bancarios_pj_agencia": null,
            "dados_bancarios_pj_banco": null,
            "dados_bancarios_pj_chave_pix": null,
            "dados_bancarios_pj_conta": null,
            "data_nascimento": "1987-11-25",
            "deleted_at": null,
            "email": "influenciador@teste.com.br",
            "email_responsavel_mailing": null,
            "endereco": "R SANTA JUSTINA 411, APTO 36           ",
            "estado": null,
            "estado_civil": null,
            "estado_nascimento": null,
            "etnia": null,
            "filhos": null,
            "formacao": null,
            "frase_destaque": "Minha frase de destaque",
            "influenciador_id": 21,
            "last_modified_by": 21,
            "last_time": "2021-10-30T16:36:34+00:00",
            "login_instagram": "instagram",
            "login_twitter": null,
            "manequim_baixo": 40,
            "manequim_cima": 38,
            "marca_dedicada": null,
            "nome": "Isabela", //THIS
            "nome_artistico": "Influenciador Teste",
            "nome_responsavel_mailing": null,
            "numero_sapato": null,
            "numero_seguidores_instagram": 404000000,
            "numero_soutien": null,
            "percentual_comissao": null,
            "periodo_dedicado": null,
            "peso": null,
            "pessoa_id": 21,
            "pets": null,
            "quadril_cms": null,
            "razao_social": null,
            "responsavel": 3,
            "responsavel_id": 3,
            "rg": "26.108.098-2",
            "sexo": "M",
            "sobrenome": "Soller", //THIS
            "telefone": "(11) 9999-9999",
            "telefone_responsavel_mailing": null,
            "texto": null,
            "tipo_cabelo": null,
            "token_senha": "9738873473ADFD6464169415AA5CB4E1E39982E2E90F11D37E8B9383FE72040B6452C98774CB0E7B",
            "url": null,
            "url_facebook": null,
            "url_media_kit": null,
            "url_youtube": null,
            "valor_pacote_fotos": 0.00,
            "valor_post": 0.00,
            "valor_post_facebook": 0.00,
            "valor_post_stories": 0.00,
            "valor_presenca": 0.00,
            "valor_shooting": 0.00,
            "valor_stories": 0.00,
            "valor_take_over": 0.00,
            "valor_video": 0.00,
            "valor_youtube": 0.00
        },
        "influenciador_id": 21,
        "job_id": 3,
        "last_modified_by": 1,
        "last_time": "2021-07-20T22:35:27+00:00",
        "nota_fiscal": false,
        "observacoes": null,
        "participacao": 100,
        "quantidade_posts": 1,
        "quantidade_presencas": 1,
        "quantidade_stories": 1,
        "status": "nao_iniciado",
        "tipo_demanda": "Espontâneo",
        "valor": 9000.00
    },
    "job_acao_comunicacoes": [],
    "job_acao_id": 4,
    "last_modified_by": 1,
    "last_time": "2021-07-20T22:35:27+00:00",
    "link_produto": null,
    "periodo": "Manhã",
    "status": "nao_iniciada",
    "tipo_acao": "Story",
    "titulo": "Um Story",
    "valor": 3000.00
}

这是我打印堆栈跟踪的错误路径。

I/flutter ( 2931): NoSuchMethodError: The method '[]' was called on null.
I/flutter ( 2931): Receiver: null
I/flutter ( 2931): Tried calling: []("nome")
I/flutter ( 2931): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:63:5)
I/flutter ( 2931): #1      new ActionPageModel.fromMap
package:soller_acessoria_new_app_nullsafety/…/actionPageModel/action_page_model.dart:45
I/flutter ( 2931): #2      ActionPageRepositoryImpl.getActionPageJobs.<anonymous closure>
package:soller_acessoria_new_app_nullsafety/…/actionPage/action_page_repository_impl.dart:28
I/flutter ( 2931): #3      bodyDecoded
package:get/…/utils/body_decoder.dart:28
I/flutter ( 2931): #4      HttpRequestImpl.send
package:get/…/io/http_request_io.dart:60
I/flutter ( 2931): <asynchronous suspension>
I/flutter ( 2931): #5      GetHttpClient._performRequest
package:get/…/src/http.dart:209
I/flutter ( 2931): <asynchronous suspension>
I/flutter ( 2931): #6      GetHttpClient.get
package:get/…/src/http.dart:455
I/flutter ( 2931): <asynchronous suspension>
I/flutter ( 2931): #7      ActionPageRepositoryImpl.getActionPageJobs
package:soller_acessoria_new_app_nullsafety/…/actionPage/action_page_repository_impl.dart:21
I/flutter ( 2931): <asynchronous suspension>
I/flutter ( 2931): #8      AcaoController.o

action_page_model中的第45行是否对应这段代码?

  influencerNome: map["influenciador"]["nome"],

如果是,问题是 influenciadorjob 的嵌套 属性,因此您收到一个 null 值,因为它不存在作为地图中的键。然后,在这个 null 值上调用 ["nome"],因此得到错误。

解决方案应该是:

  influencerNome: map["job"]["influenciador"]["nome"],