路由和导航

大多数应用程序具有多个页面或视图,并且希望将用户从页面平滑过渡到另一个页面。Flutter的路由和导航功能可帮助您管理应用中屏幕之间的命名和过渡。

管理多个页面时有两个核心概念和类:Route和 Navigator。 一个route是一个屏幕或页面的抽象,Navigator是管理route的Widget。Navigator可以通过route入栈和出栈来实现页面之间的跳转。

1.1 简单实现

以下是 routes 和 Navigator 的简单实现。

在 MaterialApp 中声明所有的路由,并在每个onTap方法中,通过Navigator 分发页面。

Navigator.pushNamed(context, '/home');//通过名称显示路由页面;
Navigator.push(context,route);//push指定路由;
Navigator.pop(context);//弹出最上面的路由;
Navigator.pop(context, true); //A dialog box might be closed with a result:
home: HomePage(), 可由 initialRoute: '/home'替代,initialRoute 参数,即系统默认的初始页面,在应用运行后就不能再更改了
import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
    title: 'My app', // used by the OS task switcher
    home: HomePage(),
    routes: <String, WidgetBuilder>{
      '/home':(BuildContext context) => HomePage(),
      '/detail':(BuildContext context) => DetailPage(),
    },
  ));
}

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

  @override
  Widget build(BuildContext context) {
    return Center(
        child: GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, '/detail');
            },
            child: Text('首页,点击跳转详情页[Navigator.pushNamed]',
                style: TextStyle(
                    fontSize: 20.0,
                    color: Colors.white, decoration: TextDecoration.none))));
  }
}

class DetailPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
        child: GestureDetector(
            onTap: () async {
              Navigator.pop(context);
               bool? value = await Navigator.push(context, MaterialPageRoute<bool>(
                 builder: (BuildContext context) {
                   return Center(
                     child: GestureDetector(
                       child: Text('OK'),
                       onTap: () { Navigator.pop(context, true); }
                     ),
                   );
                 }
               ));
               print('value:'+value.toString());
            },
            child: Text('详情页,点击跳转首页[Navigator.pop]',
                style: TextStyle(
                    fontSize: 20.0,
                    color: Colors.white, decoration: TextDecoration.none))));
  }
}
GestureDetector 继承自 StatelessWidget,是一个手势小部件。拥有点击,双点击,长按,水平滑动、垂直滑动等手势,可以包含child。这里不做展开详细介绍,自己找demo或之后再补充。
MaterialPageRoute:A modal route that replaces the entire screen with a platform-adaptive transition.

1.2 Navigator 参数传递

接受参数有两种方式,示例一:在路由的 build 方法获取参数:

import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
    title: 'My app', // used by the OS task switcher
    home: HomePage(),
    routes: <String, WidgetBuilder>{
      '/home':(BuildContext context) => HomePage(),
      '/detail':(BuildContext context) => DetailPage(),
    },
  ));
}

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

  @override
  Widget build(BuildContext context) {
    return Center(
        child: GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, '/detail',arguments:CustomArgumnets("This is HomePage params!")).then((value){
                print("value-->"+value.toString());
              });
            },
            child: Text('首页,点击跳转详情页[Navigator.pushNamed]',
                style: TextStyle(
                    fontSize: 20.0,
                    color: Colors.white, decoration: TextDecoration.none))));
  }
}

class DetailPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    CustomArgumnets customArgumnets = ModalRoute.of(context)?.settings.arguments as CustomArgumnets;
    return Center(
        child: GestureDetector(
            onTap: () async {
              Navigator.pop(context,"This is a DetailPage return params!");
            },
            child: Text('详情页,点击跳转首页[Navigator.pop],传递过来的参数为:'+customArgumnets.content,
                style: TextStyle(
                    fontSize: 20.0,
                    color: Colors.white, decoration: TextDecoration.none))));
  }
}


class CustomArgumnets {
  String content;
  CustomArgumnets(this.content);
}

示例二:通过构造函数获取参数

import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
    title: 'My app', // used by the OS task switcher
    home: HomePage(),
    routes: <String, WidgetBuilder>{
      '/home':(BuildContext context) => HomePage(),
      '/detail': (context, {arguments}) => DetailPage(content: ModalRoute.of(context)?.settings.arguments as String),
    },
  ));
}

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

  @override
  Widget build(BuildContext context) {
    return Center(
        child: GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, '/detail',arguments:"This is HomePage params!").then((value){
                print("value-->"+value.toString());
              });
            },
            child: Text('首页,点击跳转详情页[Navigator.pushNamed]',
                style: TextStyle(
                    fontSize: 20.0,
                    color: Colors.white, decoration: TextDecoration.none))));
  }
}

class DetailPage extends StatelessWidget {
  final String content;

  const DetailPage({Key? key, required this.content}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
        child: GestureDetector(
            onTap: () async {
              Navigator.pop(context,"This is a DetailPage return params!");
            },
            child: Text('详情页,点击跳转首页[Navigator.pop],传递过来的参数为:$content',
                style: TextStyle(
                    fontSize: 20.0,
                    color: Colors.white, decoration: TextDecoration.none))));
  }
}



源码地址:GitHub - hhbbeijing/flutter_app_test

Logo

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

更多推荐