flutter页面跳转及返回

一.flutter 中使用Navigator在页面之间跳转介绍

1.Navigator.push

  @optionalTypeArgs
  static Future<T?> push<T extends Object?>(BuildContext context, Route<T> route) {
    return Navigator.of(context).push(route);
  }

 Navigator.push需要传入两个参数,分别为context和下一跳转的路由,eg :

Navigator.push(context, new MaterialPageRoute(builder: (context)=>new SecondPage()));

2.Navigator.pop

  @optionalTypeArgs
  static void pop<T extends Object?>(BuildContext context, [ T? result ]) {
    Navigator.of(context).pop<T>(result);
  }

 Navigator.pop返回上一个页面,需要传入context,且上一页面必须存在,即之前有使用 Navigator.push,eg:

Navigator.pop(context);

二.创建两个页面,FirstPage和SecondPage,eg:

class FirstPage extends StatelessWidget{
  const FirstPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('第一页'),
      ),
      body: new Center(
        child: new RaisedButton(
          onPressed: (){//点击进入第二页
            Navigator.push(context, new MaterialPageRoute(builder: (context)=>new SecondPage()));
            },
          child: Text('进入第二页'),
        ),
      ),
    );
  }
  
}

class SecondPage extends StatelessWidget{
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('第二页'),
      ),
      body: new Center(
        child: new RaisedButton(
          onPressed: () {//点击返回第一页
            Navigator.pop(context);
          },
          child: Text('返回') ,
        ),
      ),
    );
  }

}

三.demo直接默认显示第一个页面FirstPage,eg:

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        brightness: Brightness.dark,
        primaryColor: Colors.blue,
        accentColor: Colors.white,
        iconTheme: IconThemeData(color: Colors.green),
        textTheme: TextTheme(bodyText1: TextStyle(color: Colors.black38
        ))
      ),
      home: Scaffold(
      body: Center(
        child: FirstPage(),
      ),
    ));

四.效果显示

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值