Flutter 界面简单跳转示例(路由)

两种方式跳转

//直接跳转
  Navigator.push(context,
      new MaterialPageRoute(builder: (context) => new SecondPage())
  );

 命名路由

Future pushNamed(BuildContext context, String routeName)

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      title: "Material App 跳转",
      home: new MyHomePage(),
      //注册路由表  使用 pushNamed(BuildContext context, String routeName)方式
      routes: {
        "/first": (BuildContext context) => FirstPage(),
        "/second": (BuildContext context) => SecondPage()
      },

      initialRoute: "/first",
    );
  }
}

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      title: "Material App 跳转",
      home: new MyHomePage(),
      //注册路由表  使用 pushNamed(BuildContext context, String routeName)方式
      routes: {
        "/first": (BuildContext context) => FirstPage(),
        "/second": (BuildContext context) => SecondPage()
      },
      initialRoute: "/first",
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("这是第二个界面"),
      ),
      body: new Center(
        child: new RaisedButton(onPressed: (){
          Navigator.pushNamed(context, "/first");
        },
        child: new Text("命名路由方式 跳转到第一个界面"),
        ),
      ),
    );
  }
}

class FirstPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("这是第一个页面"),
      ),
      body: new Center(
        child: new RaisedButton(
          onPressed: () {
//            Navigator.pushNamed(context, "/second");
          //直接跳转
            Navigator.push(context,
                new MaterialPageRoute(builder: (context) => new SecondPage())
            );
          },
          child: new Text("直接跳转方式跳转到第二个页面"),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("MaterialApp 跳转实例"),
      ),
      body: new Center(
        child: new Text(
          "主页",
          style: new TextStyle(
            fontSize: 28,
          ),
        ),
      ),
    );
  }
}

     

参考:Flutter 技术入门与实战

猜你喜欢

转载自blog.csdn.net/u013788239/article/details/89475361