Home > Mobile >  Flutter Value Null Can't Be Returned From a Function with Return Type Not Nullable
Flutter Value Null Can't Be Returned From a Function with Return Type Not Nullable

Time:03-20

List<Todo> todoFromFirestore(QuerySnapshot snapshot) {
    if (snapshot != null) {
      return snapshot.docs.map((e) {
        return Todo(
          isComplet: e.data()["isComplet"],
          title: e.data()["title"],
          uid: e.id,
        );
      }).toList();
    }
    else {
      return null;
    }
  }

this code worked in firebase_core version 0.5.3 but it's not working now(1.13.1). the Error says :

Error: The operator '[]' isn't defined for the class 'Object?'.
 - 'Object' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a '[]' operator.
          isComplet: e.data()["isComplet"],
                             ^

Error: The value 'null' can't be returned from a function with return type 'List<Todo>' because 'List<Todo>' is not nullable.
 - 'List' is from 'dart:core'.
 - 'Todo' is from 'package:simplest_todo/model/todo.dart' ('lib/model/todo.dart').
      return null;

how can i fix this code or create a new one with same function?

CodePudding user response:

First Error:

Error: The operator '[]' isn't defined for the class 'Object?'.

  • 'Object' is from 'dart:core'. Try correcting the operator to an existing operator, or defining a '[]' operator. isComplet: e.data()["isComplet"],

Problem:

The error is showing because the updated firebase library requires you to specify the type of the data.

Solution:

You can cast e.data() to Map<String, dynamic>. For more information, check out the migration guide.

Change this:

e.data()["isComplet"]

to this:

(e.data() as Map<String, dynamic>)["isComplet"]

Second Error:

Error: The value 'null' can't be returned from a function with return type 'List' because 'List' is not nullable.

  • 'List' is from 'dart:core'.
  • 'Todo' is from 'package:simplest_todo/model/todo.dart' ('lib/model/todo.dart'). return null;

Problem:

You are trying to return null from a method with a non-null return type.

Solution:

You need to make the return type of the method nullable. You do this by adding a question mark (?) after the return type.

For more information, check out Sound null safety | Dart.

Change this:

List<Todo> todoFromFirestore(QuerySnapshot snapshot) {
...
}

to this:

List<Todo>? todoFromFirestore(QuerySnapshot snapshot) {
...
}

Final Code:

Your updated code will be this below:

List<Todo>? todoFromFirestore(QuerySnapshot snapshot) {
    if (snapshot != null) {
      return snapshot.docs.map((e) {
        final Map<String, dynamic> data = e.data() as Map<String, dynamic>;
        return Todo(
          isComplet: data["isComplet"],
          title: data["title"],
          uid: e.id,
        );
      }).toList();
    }
    else {
      return null;
    }
}
  • Related