Flutter的路由使用有两种方式,分别是新建路由和注册路由。

新建路由
  • 代码如下:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
   Widget build(BuildContext context){
    return MaterialApp(
      title: "Welcome to Flutter",
      home: FirstPage(),
    );
  }
}

/// 第一个页面
class FirstPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("第一页"),
      ),
      body: Padding(
        padding: EdgeInsets.all(30.0),
        child: RaisedButton(
          child: Text('跳转到第二页'),
          onPressed: (){
            Navigator.push(//在路由栈添加路由
              context,
              MaterialPageRoute(builder: (context) => SecondPage())
            );
          },
        ),
      ),
    );
  }
}

///第二个页面
class SecondPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("第二页"),
      ),
      body: Padding(
        padding: EdgeInsets.all(30.0),
        child: RaisedButton(
          child: Text("回到第一页"),
          onPressed: (){//在路由栈移除路由
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}
注册路由

它以堆叠的方式,叠加页面。因此,在返回第一个页面的时候,需要从栈中销毁第二个页面,否则,会再次堆叠一个新的页面,就像Web前端的页面一样。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
   Widget build(BuildContext context){
    return MaterialApp(
      title: "Welcome to Flutter",
      home: FirstPage(),
      routes: <String, WidgetBuilder>{
        '/first':(BuildContext context) => FirstPage(),
        '/second':(BuildContext context) => SecondPage(),
      },
      initialRoute: 'first',
    );
  }
}

/// 第一个页面
class FirstPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("第一页"),
      ),
      body: Padding(
        padding: EdgeInsets.all(30.0),
        child: RaisedButton(
          child: Text('跳转到第二页'),
          onPressed: (){
            Navigator.pushNamed(context, '/second');
          },
        ),
      ),
    );
  }
}

///第二个页面
class SecondPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("第二页"),
      ),
      body: Padding(
        padding: EdgeInsets.all(30.0),
        child: RaisedButton(
          child: Text("回到第一页"),
          onPressed: (){
            Navigator.of(context).pop();
          },
        ),
      ),
    );
  }
}
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐