简体   繁体   English

Dart - 当我们输入的密钥错误时,我可以处理来自 json.decode 的 null 值吗

[英]Dart - Can I handle null value from json.decode when the key we put is wrong

Can we handle null value output from json.decode?我们可以处理来自 json.decode 的 null 值 output 吗? I already try using if else function, but it doesn't really works well.我已经尝试过使用 if else function,但效果并不好。

import 'dart:convert';
var typeCat = "WrongKey";
var endPoint = "WrongKey";

void main() async {
  final base = RetryClient(http.Client());
  String outputJSON = await base.read(
      Uri.parse("http://estra-api.herokuapp.com/api/${typeCat}/${endPoint}"));
  final link_decode = json.decode(outputJSON)["link"] as String;
  final text_decode = json.decode(outputJSON)["text"] as String;
  print(link_decode);
  print(text_decode);
}

Is there anything I can do with these codes?我可以用这些代码做些什么吗?

I can't be 100% sure since you didn't share the full error message, but the problem seem to be that you're trying to cast to a non-nullable String a value that can possibly be null .我不能 100% 确定,因为您没有分享完整的错误消息,但问题似乎是您正在尝试将可能是null的值转换为non-nullable String

  final link_decode = json.decode(outputJSON)["link"] as String?;
  final text_decode = json.decode(outputJSON)["text"] as String?;

and if you want to assign a default value for them you can also:如果您想为它们分配默认值,您还可以:

  final link_decode = json.decode(outputJSON)["link"] ?? 'default';
  final text_decode = json.decode(outputJSON)["text"] ?? 'default';

This will allow link_decode and text_decode to have null as value这将允许link_decodetext_decodenull作为值

Try this and if you don't succede share the error message.试试这个,如果你不成功分享错误信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM