Home > Software design >  The body might complete normally, causing 'null' to be returned, but the return type, 
The body might complete normally, causing 'null' to be returned, but the return type, 

Time:12-30

guys, future, I'm just starting to learn about the Await async structures, and I got this mistake

import 'dart:html';

class product{
  late int id;
  late String name;
  late String category;
  late int prize; 


  Map<String,dynamic> toMap(){
    var map = Map<String,dynamic>();
    map["name" ] = name;
    map["category"] = category;
    map["prize"] = prize;
    if(id==null){
      map["id"]=id;
    }
  }

 

CodePudding user response:

this is not related to async and await, you defined the function to return a Map<String, dynamic> but you are not returning anything, you can solve it by adding return map at the end of the function, but generally speaking you should study programming first and then dive into asynchronous functions, as you will find it harder this way, so better start with the fundamentals

CodePudding user response:

You are missing the return statement in the function. Add this:

return map;

But there are also several other things wrong with your class.

  1. toMap() will crash when any of the variables isn't initialized yet.
  2. Checking on if(id==null){ doesn't make much sense, as id cannot be null. id might be not initialized yet, but that's not the same as being null and that would actually crash the function as mentioned by 1.
  3. Instead of using late variables, I'd suggest to make them nullable instead. This you can do by writing int? id; for example instead of late int id;
  4. I would suggest adding a constructor to fill the variables on creation
  5. Class names are typically written with a capital letter, so like Product. It still works the way you wrote it, but it's against coding conventions.

How I might write that class:

class Product {
  int? id;
  String? name;
  String? category;
  int? prize;

  Product({this.id, this.name, this.category, this.prize});

  Map<String, dynamic> toMap() =>
      {'name': name, 'category': category, 'prize': prize, 'id': id};
}
  • Related