Flutter - Push and Get value between routes

前端 未结 5 2003
终归单人心
终归单人心 2021-02-04 02:25

How do I send the green string from the HomePage page to the ContaPage page?

I think it\'s so Navigator.of(context).pushNamed(\'/conta/green\'); but I do no

5条回答
  •  既然无缘
    2021-02-04 02:45

    A better solution is already given on Flutter website, how to use:

    Arguments

    class ScreenArguments {
      final String title;
      final String message;
    
      ScreenArguments(this.title, this.message);
    }
    

    Extract arguments

    class ExtractArgumentsScreen extends StatelessWidget {
      static const routeName = '/extractArguments';
    
      @override
      Widget build(BuildContext context) {
        final ScreenArguments args = ModalRoute.of(context).settings.arguments;
        return Scaffold(
          appBar: AppBar(
            title: Text(args.title),
          ),
          body: Center(
            child: Text(args.message),
          ),
        );
      }
    }
    

    Register Route

    MaterialApp(
      //...
      routes: {
        ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),
        //...
      },     
    );
    

    Navigate

    Navigator.pushNamed(
          context,
          ExtractArgumentsScreen.routeName,
          arguments: ScreenArguments(
            'Extract Arguments Screen',
            'This message is extracted in the build method.',
          ),
        );
    

    Code copied from link.

提交回复
热议问题