Flutter学习-命名路由

命名路由+参数传递

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '命名路由',
      initialRoute: '/', //应用首页
      routes: {
        //注册路由表
        '/': (context) => NamedRoute(),
        'second_page': (context) => SecondPage(),
        'third_page': (context) {
          return ThirdPage(
            text: ModalRoute.of(context).settings.arguments,    //传参配置
          );
        }
      },
    );
  }
}

class NamedRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('命名路由demo'),
        ),
        body: Center(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('toSecondPage'),
              onPressed: () {
                Navigator.pushNamed(context, 'second_page', arguments: '传值成功'); //命名路由跳转、传值
              },
            ),
            RaisedButton(
              child: Text('toThirdPage'),
              onPressed: () async { //异步函数
                var result = await Navigator.pushNamed(context, 'third_page',
                    arguments: '传值给第三页面');
                print('返回值:$result');   //打印返回值
              },
            )
          ],
        )));
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var args = ModalRoute.of(context).settings.arguments;   //接收传过来的参数
    return Scaffold(
      appBar: AppBar(
        title: Text('SecondPage'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[Text('路由2'), Text(args)],
        ),
      ),
    );
  }
}

class ThirdPage extends StatelessWidget {
  ThirdPage({Key key, @required this.text}) : super(key: key);  //接收参数
  final String text;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Third Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(text),
            RaisedButton(
              onPressed: () => Navigator.pop(context, '我是返回值'),
              child: Text('返回'),
            )
          ],
        ),
      ),
    );
  }
}

运行效果:
在这里插入图片描述
在这里插入图片描述 在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值