I am flutter beginner. I'm trying to connect the API to the UI using GetX, I got an error on the API service class.
Error line:
static Future fetchProducts() async
Error in fetch Products():
The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr', is a potentially non-nullable type.
Can anyone help me to solve this? Thanks in advance!
API Code:
import 'package:http/http.dart' as http;
import 'package:practice/productmodule/models/product_model.dart';
import 'package:get/get.dart';
class ApiService {
static var client = http.Client();
static Future<ProductModel> fetchProducts() async {
var response =
await client.get(Uri.parse('https://....../1'));
if (response.statusCode == 200) {
var jsonString = response.body;
return productModelFromJson(jsonString);
}}
}
You are only returning the response inside the if
block. Consider throwing an Exception
or returning an error response in JSON format like so:
import 'package:http/http.dart' as http;
import 'package:practice/productmodule/models/product_model.dart';
import 'package:get/get.dart';
class ApiService {
static var client = http.Client();
static Future<ProductModel> fetchProducts() async {
var response =
await client.get(Uri.parse('https://....../1'));
if (response.statusCode == 200) {
var jsonString = response.body;
return productModelFromJson(jsonString);
}else{
return ({'error':'Please try again later.'});
}
}
}