I'm using http package, and I want to detect null response (in case of a wrong url). I tested this example on DartPad:
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
void main(List<String> arguments) async {
// This example uses the Google Books API to search for books about http.
// https://developers.google.com/books/docs/overview
var url =
Uri.https('www.googl', '/books/v1/volumes', {'q': '{http}'});
// Await the http get response, then decode the json-formatted response.
var response ;
try{
response = await http.get(url);
}
on Exception catch (_) {
print(response.toString().isEmpty);
print(response.statusCode.toString());
print(response.body.isNotEmpty);
print(response.headers.isEmpty);
}
if (response.statusCode == 200) {
var jsonResponse =
convert.jsonDecode(response.body) as Map<String, dynamic>;
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
} else {
print('Request failed with status: ${response.statusCode}.');
}
}
And that is what I get as output:
false
Uncaught Error: NoSuchMethodError: method not found: 'get$body' on null
In this case response.toString()
is not NULL, so how can I detect if the response was null?
CodePudding user response:
Can't you check if the response
and the response.body
are different than null? The HTTP package is null safe so doing something like response?.body
can also help.
Also in the catch, you should not print out the response and instead print out an error. Because you will never have a valid response.
CodePudding user response:
You can print response.body
in the fetch function:
print(response.body);