Reputation: 61
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'. got red line under "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');
}
}
Upvotes: 1
Views: 436
Reputation: 1638
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'
.
Upvotes: 0