天天看點

Flutter中的基本路由使用

Flutter 中通過 Navigator 元件管理路由導航,并提供了管理堆棧的方法。

常用的方法如下:

1. Navigator.push 跳轉到指定頁面;

2. Navigator.pop 傳回上一級頁面;

跳轉代碼示例:

import "package:flutter/material.dart";
// 引入要跳轉到的子頁面
import '../Form.dart';

// 定義一個有狀态元件
class CategoryPage extends StatefulWidget {
    CategoryPage({Key key}) : super(key: key);
    _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
    @override
    Widget build(BuildContext context) {
        return Column(
            // 主軸對齊式式
            mainAxisAlignment:MainAxisAlignment.center,
            // 交叉軸對齊方式
            crossAxisAlignment: CrossAxisAlignment.center,
            children:<Widget>[
                RaisedButton(
                    child: Text("跳轉到表單頁面并傳值"),
                    // 點選事件
                    onPressed: () {
                        // 路由約定俗成的寫法,傳回要跳轉到的元件即可;
                        Navigator.of(context).push(
                            // 在FormPage()裡傳入參數
                            MaterialPageRoute(builder: (context)=>FormPage(title:'我是跳轉傳值的頁面'))
                        );
                    },
                    color: Theme.of(context).accentColor,
                    textTheme: ButtonTextTheme.primary
                )
            ]
        );
    }
}           

複制

效果圖如下:

Flutter中的基本路由使用

要跳轉到的子頁面FormPage,并接受參數。

import 'package:flutter/material.dart';

// 表單子頁面
class FormPage extends StatelessWidget {
    String title;
    // 在構造函數裡接受其他頁面的傳參
    FormPage({this.title="表單"});

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            // 浮動按鈕
            floatingActionButton: FloatingActionButton(
                child: Text('傳回'),
                // 點選事件
                onPressed: (){
                    // 自定義傳回上一級頁面
                    Navigator.of(context).pop();
                },
            ),
            appBar: AppBar(
                title:Text(this.title)
            ),
            body: ListView(
                children: <Widget>[
                    ListTile(
                        title:Text('這是表單頁面')
                    ),
                    ListTile(
                        title:Text('這是表單頁面')
                    ),
                    ListTile(
                        title:Text('這是表單頁面')
                    ),
                    ListTile(
                        title:Text('這是表單頁面')
                    )
                ]
            ),
        );
    }
}           

複制

效果圖如下:

Flutter中的基本路由使用

頁面跳轉時,手機頂部導覽列是有預設的傳回按鈕的,如果想自定義傳回上一級頁面,可以通過 Navigator.of(context).pop() 來傳回上一級頁面,詳見上面子頁面的代碼。