Home > Enterprise >  The body might complete normally, causing 'null' to be returned flutter
The body might complete normally, causing 'null' to be returned flutter

Time:10-01

I created a function to fetch data through api and now I'm trying to check from the data value of this function, but every time I get the following error:

The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr<List<AllProductModel>>', is a potentially non-nullable type.

my function:

Future <List<AllProductModel>> fetchYourProduct(Uid) async {
  final url =
      'https://*****************.php?UserPost='   Uid.toString();
  final response = await http.get(Uri.parse(url));
  final body = json.decode(response.body);
  if (json.decode(response.body)!="Data not found") { //here problem 
    return body.map<AllProductModel>(AllProductModel.fromJson).toList();
  }else{

  }
}

I try to make if statement to see if the data I get from api same string I was add or not. The function without if statement it's working fine but I need to add if statement.

Data model:


class AllProductModel {

  String? name;
 

  AllProductModel(
      {
        this.name,
      
 });

  static AllProductModel  fromJson(json) => AllProductModel(
 
    name : json['name'].toString(),

  );
  }


How I can solve this problem?

Thank you.

CodePudding user response:

With a function that has a non-nullable return type (return can't be null), you need to return that type in every possible case inside that function (or throw an exception).

For example, your function returns a Future<List<AllProductModel>>. This is not nullable, hence, for every single case of your function, you must either:

  1. Return that specified type; or
  2. Do a throw statement, like this: throw <some_exception>

You return something inside the if clause of your statement, however, you don't return anything inside the else clause. That's your problem.

Solution: Either return something inside that else clause, or throw an exception.

CodePudding user response:

You can also try and check if this works..

You can make the fetchYourProduct() function nullable by changing the return type from Future <List> to Future <List>?.

CodePudding user response:

Future <List> fetchYourProduct(Uid) async { final url = 'https://*****************.php?UserPost=' Uid.toString(); final response = await http.get(Uri.parse(url)); final body = json.decode(response.body); if (json.decode(response.body)!="Data not found") { //here problem return body.map(AllProductModel.fromJson).toList(); }else{ return []; } }

you should to return If and else both of statement compulsory.

  • Related