i'm using http package . so i want to detect that i have a null response so that is normally in case of a wrong url . so i tested this example on DartPad . this is the example :
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
so in this case response.toString()
is not NULL so how can i detect if the response is null ?
CodePudding user response:
You can print the response.body in the fetch function print(response.body);
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.