Flutter应用导航管理插件app_navigator的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter应用导航管理插件app_navigator的使用

App Navigator 是一个基于 Flutter 的 Navigator 实现的声明式导航管理器,旨在使代码更加简洁易用。它利用了 Flutter 的 Navigator v2.0 版本。

功能

  • 易于集成与使用
  • 使用 Flutter 的 Navigator v2.0

开始使用

添加依赖

在你的 pubspec.yaml 文件中添加 app_navigator 包作为依赖:

flutter pub add app_navigator

导入包

在你的 Dart 文件中导入 app_navigator 包:

import 'package:app_navigator/app_navigator.dart';

使用示例

初始化

首先,在你的主应用程序中初始化 NavigationLayer

import 'package:flutter/material.dart';
import 'package:app_navigator/app_navigator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AppNavigator Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: NavigationLayer(
        initPage: Page1(),
        initPath: Page1.route,
      ),
    );
  }
}

导航

推送页面

使用 AppNavigator.push 方法来导航到新页面:

onTap() => AppNavigator().push(Page2(), name: Page2.route);

返回上一页

使用 AppNavigator.pop 方法返回上一页:

onTap() => AppNavigator().pop();

返回指定页面

使用 AppNavigator.popUntilNamed 方法返回到指定路径的页面:

onTap() => AppNavigator().popUntilNamed(Page1.route);

页面示例

以下是三个示例页面的完整代码:

class Page1 extends StatelessWidget {
  static const String route = 'home';

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Page_1'),
            Padding(
              padding: const EdgeInsets.only(left: 8.0),
              child: Text(
                AppNavigator().currentPath ?? 'no path',
                style: TextStyle(
                    fontStyle: FontStyle.italic, fontWeight: FontWeight.w200),
              ),
            ),
          ],
        ),
      ),
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(AppNavigator()
                  .navigationRoutes
                  .fold('Stack', (initial, value) => '$initial -> $value')),
              ElevatedButton(
                child: Text('Go to Page 2'),
                onPressed: () =>
                    AppNavigator().push(Page2(), name: Page2.route),
              ),
              ElevatedButton(
                child: Text('Push replacement'),
                onPressed: () => AppNavigator()
                    .pushAndReplaceAllStack(Page2(), name: Page2.route),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  static const String route = 'page2';

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Page_2'),
            Padding(
              padding: const EdgeInsets.only(left: 8.0),
              child: Text(
                AppNavigator().currentPath ?? 'no path',
                style: TextStyle(
                    fontStyle: FontStyle.italic, fontWeight: FontWeight.w200),
              ),
            ),
          ],
        ),
      ),
      body: Container(
        child: Center(
          child: Column(
            children: [
              Text(AppNavigator()
                  .navigationRoutes
                  .fold('Stack', (initial, value) => '$initial -> $value')),
              ElevatedButton(
                child: Text('Go to Page 3'),
                onPressed: () =>
                    AppNavigator().push(Page3(), name: Page3.route),
              ),
              ElevatedButton(
                child: Text('Dialog'),
                onPressed: () => AppNavigator().showDialog(
                  builder: (context) => SimpleDialog(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20)),
                    contentPadding: const EdgeInsets.all(12),
                    title: const Text(
                      'Warning',
                      textAlign: TextAlign.center,
                    ),
                    titleTextStyle: const TextStyle(
                      fontSize: 16,
                      color: Colors.black,
                      fontWeight: FontWeight.w700,
                    ),
                    children: [
                      const Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Text(
                          'Do you really want to exit?',
                          textAlign: TextAlign.center,
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              primary: Colors.white,
                              side: const BorderSide(
                                color: Colors.red,
                              ),
                              padding: const EdgeInsets.symmetric(
                                  vertical: 5, horizontal: 10),
                            ),
                            onPressed: () {
                              AppNavigator().pop();
                            },
                            child: Text(
                              'No',
                              style: const TextStyle(
                                  color: Colors.red,
                                  fontSize: 16,
                                  fontWeight: FontWeight.w700),
                            ),
                          ),
                          ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 5, horizontal: 10),
                              textStyle: const TextStyle(
                                  fontSize: 16, fontWeight: FontWeight.w700),
                            ),
                            onPressed: () {
                              // Navigator.of(context).pop(true);
                              AppNavigator().pop();
                            },
                            child: Text('yes'),
                          )
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              ElevatedButton(
                child: Text('Pop'),
                onPressed: () {
                  AppNavigator().pop();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Page3 extends StatelessWidget {
  static const String route = 'page3';

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Page_3'),
            Padding(
              padding: const EdgeInsets.only(left: 8.0),
              child: Text(
                AppNavigator().currentPath ?? 'no path',
                style: TextStyle(
                    fontStyle: FontStyle.italic, fontWeight: FontWeight.w200),
              ),
            ),
          ],
        ),
      ),
      body: Container(
        child: Center(
          child: Column(
            children: [
              Text(AppNavigator()
                  .navigationRoutes
                  .fold('Stack', (initial, value) => '$initial -> $value')),
              ElevatedButton(
                child: Text('popUntilNamed Page1'),
                onPressed: () => AppNavigator().popUntilNamed(Page1.route),
              ),
              ElevatedButton(
                child: Text('Pop'),
                onPressed: () {
                  AppNavigator().pop();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter应用导航管理插件app_navigator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter应用导航管理插件app_navigator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter应用中使用app_navigator插件进行导航管理的示例代码。app_navigator插件通常用于简化和集中管理Flutter应用中的路由导航。不过需要注意的是,app_navigator并不是一个广泛认知的官方或流行的Flutter插件,这里我将以一个通用的导航管理示例为基础,展示如何实现类似功能。

在实际应用中,如果你确实有一个名为app_navigator的特定插件,请参考其官方文档调整代码。以下示例将使用Flutter的内置导航功能来模拟一个导航管理器的实现。

1. 设置项目依赖

首先,确保你的pubspec.yaml文件中包含了必要的依赖项,主要是flutter本身,因为我们将使用Flutter内置的路由功能。

dependencies:
  flutter:
    sdk: flutter

2. 创建路由配置

接下来,我们创建一个路由配置类来管理所有的路由。

import 'package:flutter/material.dart';
import 'package:your_app/screens/home_screen.dart';
import 'package:your_app/screens/detail_screen.dart';

class AppRoutes {
  static const String home = '/';
  static const String detail = '/detail';

  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case home:
        return MaterialPageRoute(builder: (_) => HomeScreen());
      case detail:
        final String? itemId = settings.arguments as String?;
        return MaterialPageRoute(builder: (_) => DetailScreen(itemId: itemId!));
      default:
        return MaterialPageRoute(builder: (_) => Scaffold(body: Center(child: Text('No route defined for ${settings.name}'))));
    }
  }
}

3. 设置MaterialApp

main.dart中,我们将MaterialApponGenerateRoute属性设置为AppRoutes.generateRoute

import 'package:flutter/material.dart';
import 'package:your_app/routes/app_routes.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: AppRoutes.home,
      onGenerateRoute: AppRoutes.generateRoute,
    );
  }
}

4. 创建示例屏幕

创建两个简单的屏幕:HomeScreenDetailScreen

HomeScreen.dart

import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Screen'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pushNamed(context, AppRoutes.detail, arguments: 'item123');
          },
          child: Text('Go to Detail'),
        ),
      ),
    );
  }
}

DetailScreen.dart

import 'package:flutter/material.dart';

class DetailScreen extends StatelessWidget {
  final String itemId;

  DetailScreen({required this.itemId});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Detail Screen'),
      ),
      body: Center(
        child: Text('Detail for $itemId'),
      ),
    );
  }
}

5. 运行应用

现在,你可以运行你的Flutter应用。当你点击HomeScreen上的按钮时,应用将导航到DetailScreen并显示传递的itemId

这个示例展示了如何使用Flutter的内置功能来管理应用中的路由。如果你有一个特定的app_navigator插件,请查阅其文档以了解如何集成和使用它,但大多数导航管理插件的基本用法都会遵循类似的模式。

回到顶部