flutter2.x报错解决type (RouteSettings) => Route <dynamic>? is not a subtype of type (RouteSettings) => Route <dynemic> of function result
原有代码--main.dart
import 'package:flutter/material.dart';
import 'pages/tabs/Tabs.dart';
import 'routers/router.dart';
void main() {
runApp(MyApp());
}
// 输入stf 有状态组件
// stss 无状态组件
class MyApp extends StatefulWidget {
const MyApp({ Key? key }) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
// home: Tabs()
initialRoute: '/', // 注意观察--问题就出在函数类型声明方面
onGenerateRoute: onGenerateRoute, // 注意观察--问题就出在函数类型声明方面
);
}
}
原有代码--router.dart
import 'package:flutter/material.dart';
import '../pages/tabs/Tabs.dart';
import '../pages/test/Search.dart';
// 配置路由路径
var router = {
'/': (context, { arguments }) => Tabs(arguments: arguments), // 使用arguments传递参数
'/search': (context) => SearchPage()
};
// onGenerateRoute配置
// 注意观察--问题就出在函数类型声明方面
final onGenerateRoute = (RouteSettings settings) {
final String ? name = settings.name;
final Function pageContentBuilder = router[name] as Function;
if (pageContentBuilder != null) {
if (settings.arguments != null) {
final Route route = MaterialPageRoute(
builder: (context) =>
pageContentBuilder(context, arguments: settings.arguments));
return route;
} else {
final Route route =
MaterialPageRoute(builder: (context) => pageContentBuilder(context));
return route;
}
}
};
解决方案--现有代码--修改类型声明
final Map<String, WidgetBuilder> routes = {
'/': (context) => NewPage(),
'/search': (context) => ParamPage(),
};
Route<dynamic> _onGenerateRoute(RouteSettings settings) {
// return MaterialPageRoute(builder: (context) {
// // 如果访问的路由页需要登录,但当前未登录,则直接返回登录页路由,
// // 引导用户登录;其它情况则正常打开路由。
// // 统一处理
// })
final String name = settings.name;
final Function pageContentBuilder = routes[name];
print('到1');
if (settings.arguments != null) {
print('到2');
final Route route = MaterialPageRoute(
builder: (context) => NewPage(),
);
return route;
} else {
print('到3');
final Route route = MaterialPageRoute(
builder: (context) {
return ParamPage(text: ModalRoute.of(context).settings.arguments);
},
);
return route;
}
}
解决思路,点击main.dart中的 onGenerateRoute: _onGenerateRoute,跳转过去看一下其变量类型,然后根据类型进行声明