一.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(),
      ),
    ));

四.效果显示

 

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐