1

我正在尝试使用具有多个命名参数的命名路由,如下例所示,问题是如果我想将多个参数传递给屏幕,那么我需要使用这些参数定义一个自定义类。假设我有 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});
}
4

1 回答 1

1

标准方法是为每个页面定义相关类,但是您可以JSON在每个页面上创建一个字符串并将其传递给另一个页面。例如,首先在第 1 页中定义它:

String temp = json.encode({
par1:"test",
par2:"test2" // and so on
});

然后将其传递到另一个页面:

Navigator.pushNamed(
              context,
              FirstScreen.routeName,
              arguments: temp
            );

然后在另一个页面上对其进行解码:

Map<String, dynamic> data = json.decode(temp);
于 2021-08-12T11:48:21.320 回答