无法从“fetchById”方法返回“Null”类型的值,因为它的返回类型为“Location”

Muh*_*lal -1 dart flutter

static Location fetchById(int id) {
   List<Location> locations = Location.fetchAll();

   for (var i = 0; i < locations.length; i++) {
     if (locations[i].id == id) {
       return locations[i];
     }
   }
   
   return null;
}
Run Code Online (Sandbox Code Playgroud)

// 如果条件不成立,则返回 null 当我尝试返回 null 或 false 时,它​​会给出错误“无法从方法 'fetchById' 返回类型为 'Null' 的值,因为它的返回类型为 '地点'。

nic*_*101 5

使用dart 语言中的空安全功能,您必须明确告知是否要使值可以为空。

使用 a 定义返回类型?,因此 dart 知道返回值可以为 null。

static Location? fetchById(int id) 
{ 
  /// function body
}
Run Code Online (Sandbox Code Playgroud)