flutter 类型“Null”不是类型强制转换中类型“Map〈String,dynamic>”的子类型

fkvaft9z  于 2023-03-31  发布在  Flutter
关注(0)|答案(3)|浏览(175)

我有这个错误,而我想创建多个页面的动态导航..这里是下面的代码..

import 'package:flutter/material.dart';
import 'screens/locations/locations.dart';
import 'screens/location_detail.dart';

 const LocationsRoute = "/";
 const LocationDetailRout = '/location_detail';

 class App extends StatelessWidget {
   @override
   Widget build(BuildContext context) {
   return MaterialApp(
    onGenerateRoute: _routes(),
);

}

RouteFactory _routes() {
   return (settings) {
   // final Map<String, dynamic> arguments = settings.arguments;
    final arguments = settings.arguments as Map<String, dynamic>;
    Widget screen;
    switch (settings.name) {
      case LocationsRoute:
      screen = Locations();
      break;
      case LocationDetailRout:
      screen = LocationDetail(arguments['id']);
  }
};

}
}

wz3gfoph

wz3gfoph1#

快速修复

Map arguments = (settings.arguments??{}) as Map;
weylhg0b

weylhg0b2#

根据flutter官方文档https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments onGenerateRoute()函数根据给定的RouteSettings创建正确的路由。
所以我们做错的事情是我们在主块中为每个路由寻找参数(switch语句之外),但只有LocationDetailRoute路由有参数,这就是为什么我们对所有其他路由都得到null。

RouteFactory _routes() {
    return (settings) {
      Widget screen;
      switch (settings.name) {
        case LocationsRoute:
          screen = Locations();
          break;
        case LocationDetailRoute:
          // Correct Place for this Statement
          final arguments = settings.arguments as Map<String, dynamic>; 
          screen = LocationDetails(arguments['id']);
          break;
        default:
          return null;
      }
      // return MaterialPageRoute(builder: (BuildContext context) => screen);
      return MaterialPageRoute(builder: (BuildContext context) => screen, settings: settings);
    };
  }
blmhpbnm

blmhpbnm3#

RouteSettingsarguments可以是Null,这就是为什么你在这里看到错误final arguments = settings.arguments as Map<String, dynamic>;。你基本上是试图将Null转换为Map。我也不确定这是否是故意的,但你的内部函数(实际的RouteFactory)在任何情况下都不会返回Route

相关问题