_TypeError(类型 'Null' 不是类型 'FutureOr<Stations>' 的子类型)

_TypeError (type 'Null' is not a subtype of type 'FutureOr<Stations>')

最近安装了 Flutter null safety 并修复了大部分代码我在 API 调用时遇到了问题。

它returns_TypeError (type 'Null' is not a subtype of type 'FutureOr<Stations>')

我还没有找到似乎符合我的问题/代码方法的 SO 答案。

这是从 main.dart

调用 API 的按钮点击
void _anchoredMapMarkersButtonClicked() {
    _mapMarkerExample.showAnchoredMapMarkers();
  }

这是 API 调用自身,错误显示在底部 } catch(Exception) {

 Future<Stations> fetchStations() async {
    var client = http.Client();
    var stations;
     
   Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);


    var lat = position.latitude;
    var long = position.longitude;
    
try{
    var response = await client.get(Uri.parse('https call'));
    if (response.statusCode == 200) {
   var jsonString = response.body;
   var jsonMap = json.decode(jsonString);
   
   stations = Stations.fromJson(jsonMap);
   //print(stations);
  }
} catch(Exception) {
  return stations;
}

  return stations;
}

更新代码

Future<Stations> fetchStations() async {
    var client = http.Client();
    Stations? stations;
     
   Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
   print(position);


    var lat = position.latitude;
    var long = position.longitude;
    
try{
    var response = await client.get(Uri.parse('https://transit.hereapi.com/v8/stations?in=$lat,$long&return=transport&apiKey=uIioesb_EbnEXgPHlH0Z5e7gPGy9irpq2dRJcjuYPZY'));
    if (response.statusCode == 200) {
   var jsonString = response.body;
   var jsonMap = json.decode(jsonString);
   //print(jsonMap);
   inspect(jsonMap);
   
   stations = Stations.fromJson(jsonMap);
   //print(stations);
  }
} catch(Exception) {
  Future<Stations?> fetchStations()
}

  Future<Stations?> fetchStations()
}

开启null safety后,每种类型分为nullable和non-nullable类型,如下图,来自dart官方文档Non-nullable and nullable types

所以当你声明 var stations 时,默认情况下它的值为 dynamic,在 dart null safety 中它可以为 null,但是函数的 return 是type Future<Stations>,其中 future Stations 的值永远不能为空(因为它没有类型后的 ?),要解决这个问题,你必须选择:

第一个选项,

像这样声明你的站变量

Stations? stations; // you tell the compiler that this variable can hold null value

然后使函数的return

Future<Stations?> fetchStations() 

这样,您从函数中 return null 是有效的。

第二个选项,

像这样将电台声明为非空

Stations stations; // this will give a compiler error

但是现在你会遇到一个编译器错误,指出 stations 是一个非 null 类型并且你没有给它赋值,你可以给它赋一个初始值

Stations stations = Stations();

或者,使用 late 关键字,

late Stations stations; // tell the compiler that this is non null object that i'll assign a value to later

但请注意,在后者中,您必须在某个时候分配 stations 一个值,否则会出现异常。

如果您选择第一个选项,函数应该如下所示,

Future<Stations?> fetchStations() async {
    var client = http.Client();
    Stations? stations;
     
   Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);


    var lat = position.latitude;
    var long = position.longitude;
    
try{
    var response = await client.get(Uri.parse('https call'));
    if (response.statusCode == 200) {
   var jsonString = response.body;
   var jsonMap = json.decode(jsonString);
   
   stations = Stations.fromJson(jsonMap);
   //print(stations);
  }
} catch(e) {
  // you don't need to return stations, because you return it at the end of the function
  // return stations;
  print("Exception Happened: ${e.toString()}")
}
  // you can return a nullable object because the function return type is a nullable type
  return stations; 
}