Flutter NoSuchMethodError:在 null 上调用了方法“[]”。使用flutter获取api时如何解决此错误
Posted
技术标签:
【中文标题】Flutter NoSuchMethodError:在 null 上调用了方法“[]”。使用flutter获取api时如何解决此错误【英文标题】:Flutter NoSuchMethodError: The method '[]' was called on null. how to solve this error when giving get in an api using flutter 【发布时间】:2021-12-17 07:15:40 【问题描述】:我在通过 get 方法使用 api 时遇到问题。显然错误出在我的模型映射中,但至少对我来说模型没问题。如果有人可以帮助我,我将不胜感激。
这是我的方法,我正在使用 get connect 来访问 api。 _restClient 指的是我的基本网址。
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
【问题讨论】:
【参考方案1】:action_page_model
中的第 45 行是否对应此代码?
influencerNome: map["influenciador"]["nome"],
如果是,问题在于influenciador
是job
的嵌套属性,因此您会收到null
值,因为它在您的地图中不作为键存在。然后,在这个null
值上,您调用["nome"]
,因此得到错误。
解决办法应该是:
influencerNome: map["job"]["influenciador"]["nome"],
【讨论】:
谢谢我的朋友,你解决了问题,帮我解决了,非常感谢 不客气,很高兴能帮到你以上是关于Flutter NoSuchMethodError:在 null 上调用了方法“[]”。使用flutter获取api时如何解决此错误的主要内容,如果未能解决你的问题,请参考以下文章
未处理的异常:NoSuchMethodError:方法'showNotificationDaily'在flutter中被调用为null
Flutter:[cloud_firestore/unknown] NoSuchMethodError:null 上的无效成员:'includeMetadataChanges'(Flutter Web
Flutter - NoSuchMethodError:方法'visitChildren'在null上被调用
Flutter:抛出了 NoSuchMethodError。在 null 上调用了 getter 'type'
Flutter:NoSuchMethodError:方法 'fetchByID' 在 null 上被调用。接收方:null 尝试调用:fetchByID(2)