Flutter深度路由管理插件deep_route的使用

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

Flutter深度路由管理插件deep_route的使用

什么是DeepRoute?

DeepRoute 是一个用于Flutter导航的包,它需要少量代码即可生成应用程序内部所需的导航功能。 它的一个优势是不需要上下文,因此可以从业务逻辑中进行导航。

安装

pubspec.yaml 文件中添加 DeepRoute:

dependencies:
  deep_route:

在将要使用的文件中导入 DeepRoute:

import 'package:deep_route/deep_route.dart';

使用示例

步骤1: 在你的 MaterialApp 之前添加 “DeepMaterialApp”,使用 DeepMaterialApp 而不是 MaterialApp

void main() {
  runApp(DeepMaterialApp(home: Home()));
}

步骤2: 使用 DeepRoute 进行导航,例如

DeepRoute.toNamed('/RouteName', arguments: 'sample');
DeepRoute.to(NextPage());

补充信息

此包处于早期开发阶段。


示例代码

import 'package:deep_route/deep_material_app.dart';
import 'package:deep_route/deep_route.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  [@override](/user/override)
  Widget build(BuildContext context) {
    return DeepMaterialApp(
      title: 'DeepRoute Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      onGenerateRoute: (settings) {
        // 如果你推送 SecondPage 路由
        if (settings.name == SecondPage.routeName) {
          // 将参数转换为正确的类型:String。
          final args = settings.arguments as String;

          // 然后从参数中提取所需的数据并传递给正确的屏幕。
          return MaterialPageRoute(
            builder: (context) {
              return SecondPage(
                message: args,
              );
            },
          );
        }
        // 当前代码只支持 SecondPage.routeName。其他值需要实现。断言在这里会帮助我们在调用堆栈的更高位置提醒我们这一点,因为这个断言会在框架的某个地方触发。
        assert(false, 'Need to implement ${settings.name}');
        return null;
      },
      home: const MyHomePage(title: 'DeepRoute Demo Home'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'Push the button and Navigate to next page using DeepRoute',
            ),
            const SizedBox(
              height: 110,
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                  minimumSize: Size(double.maxFinite, 40)),
              onPressed: () {
                DeepRoute.to(SecondPage(
                  message: 'Normal Page Route',
                ));
              },
              child: Text('Next Page'),
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                  minimumSize: Size(double.maxFinite, 40)),
              onPressed: () {
                DeepRoute.toNamed(SecondPage.routeName,
                    arguments: 'Named Route Used');
              },
              child: Text('Next Page (Using Named Route)'),
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                  minimumSize: Size(double.maxFinite, 40)),
              onPressed: _nextPage,
              child: Text('Next Page (Without using context)'),
            ),
          ],
        ),
      ),
    );
  }

  void _nextPage() {
    DeepRoute.toNamed(SecondPage.routeName,
        arguments: 'Navigated without context');
  }
}

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key, required this.message}) : super(key: key);
  static final routeName = '/second';
  final String message;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Page')),
      body: Center(child: Text(message)),
    );
  }
}

更多关于Flutter深度路由管理插件deep_route的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter深度路由管理插件deep_route的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,关于Flutter中的深度路由管理插件deep_route的使用,以下是一个详细的代码案例来展示其基本功能和实现方式。deep_route插件允许你在Flutter应用中实现复杂的路由管理,特别是深度嵌套的场景。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加deep_route依赖:

dependencies:
  flutter:
    sdk: flutter
  deep_route: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来安装依赖。

2. 配置路由

接下来,你需要在你的应用中配置路由。通常,这会在一个单独的文件中完成,比如routes.dart

// routes.dart

import 'package:flutter/material.dart';
import 'package:deep_route/deep_route.dart';
import 'package:deep_route_example/screens/home_screen.dart';
import 'package:deep_route_example/screens/details_screen.dart';
import 'package:deep_route_example/screens/profile_screen.dart';

class AppRouter {
  static final DeepRouter router = DeepRouter(
    routes: [
      DeepRoute(
        path: '/',
        builder: (context, args) => HomeScreen(),
      ),
      DeepRoute(
        path: '/details/:id',
        builder: (context, args) => DetailsScreen(id: args['id'] as String),
      ),
      DeepRoute(
        path: '/profile/:userId/posts/:postId',
        builder: (context, args) => ProfileScreen(
          userId: args['userId'] as String,
          postId: args['postId'] as String,
        ),
      ),
    ],
  );
}

3. 使用路由

在你的main.dart文件中,你需要设置MaterialApp并使用配置的路由。

// main.dart

import 'package:flutter/material.dart';
import 'package:deep_route_example/routes.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Deep Route Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      onGenerateRoute: (settings) {
        return MaterialPageRoute(
          builder: (context) => AppRouter.router.build(settings.name, settings.arguments),
        );
      },
      initialRoute: '/',
    );
  }
}

4. 导航到不同路由

现在你可以在你的应用中使用DeepRouter提供的导航方法来导航到不同的路由。例如,在HomeScreen中:

// home_screen.dart

import 'package:flutter/material.dart';
import 'package:deep_route_example/routes.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Go to Details',
            ),
            ElevatedButton(
              onPressed: () {
                // 导航到详情页
                AppRouter.router.navigate('/details/123', context);
              },
              child: Text('Details'),
            ),
            SizedBox(height: 20),
            Text(
              'Go to Profile Post',
            ),
            ElevatedButton(
              onPressed: () {
                // 导航到用户帖子详情页
                AppRouter.router.navigate('/profile/user1/posts/post1', context);
              },
              child: Text('Profile Post'),
            ),
          ],
        ),
      ),
    );
  }
}

5. 接收路由参数

DetailsScreenProfileScreen中,你可以接收并处理路由参数。

// details_screen.dart

import 'package:flutter/material.dart';

class DetailsScreen extends StatelessWidget {
  final String id;

  DetailsScreen({required this.id});

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

// profile_screen.dart

import 'package:flutter/material.dart';

class ProfileScreen extends StatelessWidget {
  final String userId;
  final String postId;

  ProfileScreen({required this.userId, required this.postId});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Profile Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('User ID: $userId'),
            Text('Post ID: $postId'),
          ],
        ),
      ),
    );
  }
}

总结

通过上述代码,你可以在你的Flutter应用中实现深度路由管理。deep_route插件提供了灵活的路由配置和导航方法,使得管理复杂路由变得更加容易。希望这个示例对你有所帮助!

回到顶部