Aleyna Eser
Aleyna Eser

Reputation: 65

Flutter error: The body might complete normally, causing 'null' to be returned

class Word {
  int? id;
  late String word;
  late String description;

  Word({required this.word, required this.description});
  Word.withId({this.id, required this.word, required this.description});

  Map<String,dynamic> toMap(){
    var map = Map<String,dynamic>();
    map["word"] = word;
    map["description"] = description;
    if (id!=null) {
      map["id"] = id;
    }
  }

. . .

Future<int?> insert(Word word) async {
    /// db ekleme sorgusu
    Database? db = await this.db;

    /// database erişim
    var result = await db!.insert("words", word.toMap());
    return result;
  }

I am getting this error where I am using Map for this block of code can anyone help? 😕

error: The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type. (body_might_complete_normally at [sqflite_demo] lib\models\word.dart:9)

Upvotes: 0

Views: 2818

Answers (1)

Tim Jacobs
Tim Jacobs

Reputation: 1193

You have this function with a return type of Map<String, dynamic>:

  Map<String,dynamic> toMap(){
    var map = Map<String,dynamic>();
    map["word"] = word;
    map["description"] = description;
    if (id!=null) {
      map["id"] = id;
    }
  }

But this function doesn't return anything, it just assigns this Map to a variable map. You want to add a line with return map; at the bottom of your function, and things should work as you want.

  Map<String,dynamic> toMap(){
    var map = Map<String,dynamic>();
    map["word"] = word;
    map["description"] = description;
    if (id!=null) {
      map["id"] = id;
    }
    return map;
  }

Upvotes: 3

Related Questions