[英]Flutter how do i display snapshot.data of FutureBuilder?
I want to display the summoner data from riot api, but I get this error 'error: The method '[]' can't be unconditionally invoked because the receiver can be 'null'.我想显示来自 riot api 的召唤师数据,但我收到此错误“错误:无法无条件调用方法“[]”,因为接收器可以为“空”。 got red line under "return Text(snapshot.data['id'])".在“return Text(snapshot.data['id'])”下有红线。
so I tried using '?'所以我尝试使用 '?' to make it conditional, but I'm still getting the same error.使其成为有条件的,但我仍然遇到相同的错误。 Anyone knows how to handle this??有人知道怎么处理吗??
FutureBuilder(
future: getData(widget.value),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.active:
return Text('active');
case ConnectionState.waiting:
return Text('waiting,,,');
case ConnectionState.done:
return snapshot.hasData
? Text(snapshot.data['id'])
: Text('N/A');
default:
return Text('default');
Future getData(String value) async {
http.Response response =
await http.get(Uri.parse('$summonerInfoUrl$value?api_key=$apiKey'));
if (response.statusCode == 200) {
String data = response.body;
var decodeData = jsonDecode(data);
return decodeData;
} else {
print(response.statusCode);
return Text('error occured');
}
}
You need to use the null aware operator !
您需要使用空感知运算符!
before the square brackets, which will force the value to exclude null.在方括号之前,这将强制该值排除空值。 However, only do this if you are sure the response is null, else it will throw an error.但是,仅当您确定响应为空时才执行此操作,否则会引发错误。
If you are not sure if it is null, use the operator ?
如果您不确定它是否为空,请使用运算符?
before the brackets, followed by ??
在括号之前,然后是??
after the brackets and a fallback value.在括号和后备值之后。 Eg.例如。 snapshot.data?['id'] ?? 'No ID'
snapshot.data?['id'] ?? 'No ID'
. snapshot.data?['id'] ?? 'No ID'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.