我正在尝试使用具有多个命名参数的命名路由,如下例所示,问题是如果我想将多个参数传递给屏幕,那么我需要使用这些参数定义一个自定义类。假设我有 10 个屏幕要导航,所以用它的参数定义 10 个自定义类是否有意义?
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateRoute: (settings) {
if (settings.name == FirstScreen.routeName) {
final args = settings.arguments as FirstScreenArguments;
return MaterialPageRoute(
builder: (context) {
return FirstScreen(
title: args.title,
message: args.message,
);
},
);
} else if (settings.name == HomeScreen.routeName)
return MaterialPageRoute(
builder: (context) {
return HomeScreen();
},
);
assert(false, 'Need to implement ${settings.name}');
return null;
},
title: 'Navigation with named arguments',
initialRoute: HomeScreen.routeName,
);
}
}
class HomeScreen extends StatelessWidget {
HomeScreen({Key? key}) : super(key: key);
static const routeName = '/';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(
context,
FirstScreen.routeName,
arguments: FirstScreenArguments(
title: 'Welcome',
message: "Coming from home screen ",
),
);
},
child: const Text('Navigate to first screen'),
),
),
);
}
}
class FirstScreen extends StatelessWidget {
final String title;
final String message;
const FirstScreen({Key? key, required this.title, required this.message})
: super(key: key);
static const routeName = '/firstScreen';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(title),
Text(message),
],
),
),
);
}
}
class FirstScreenArguments {
final String title;
final String message;
FirstScreenArguments({required this.title, required this.message});
}