flutter实战项目(准备工作篇)go_router 作为路由框架

我们直接上代码

 不对,先在pubspec.yaml 上添加dependences

 好,现在上代码
 



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

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

/// The route configuration.
final GoRouter _router = GoRouter(
  routes: <RouteBase>[
    GoRoute(
      path: '/',
      builder: (BuildContext context, GoRouterState state) {
        return const HomeScreen();
      },
      routes: <RouteBase>[
        GoRoute(
          path: 'details',
          builder: (BuildContext context, GoRouterState state) {
            return const DetailsScreen();
          },
        ),
        GoRoute(
            path: "loging",
            builder: (BuildContext context, GoRouterState state){
              return  LogingPage();
            }
        ),
      ],



    ),
  ],
);

/// The main app.
class MyApp extends StatelessWidget {
  /// Constructs a [MyApp]
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: _router,
    );
  }
}

/// The home screen
class HomeScreen extends StatelessWidget {
  /// Constructs a [HomeScreen]
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Home Screen')),
      // body: Center(
      //   child: ElevatedButton(
      //     onPressed: () => context.go('/details'),
      //     child: const Text('Go to the Details screen'),
      //   ),
      // ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () => context.go("/details"),
              child: Text('Go to the Details screen'),
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white,  // 设置按钮文本颜色为白色
                backgroundColor: Colors.blue, // 设置按钮背景为蓝色
                padding: EdgeInsets.symmetric(vertical: 16, horizontal: 24), // 设置按钮内边距
                textStyle: TextStyle(fontSize: 16), // 设置按钮文本样式
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8), // 设置按钮圆角
                ),
              ),
            ),
            ElevatedButton(
              onPressed: () => context.go("/loging"),
              child: Text('Go to the LoginPage'),
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white, // 设置按钮文本颜色为白色
                backgroundColor: Colors.green, // 设置按钮背景为绿色
                padding: EdgeInsets.symmetric(vertical: 16, horizontal: 24), // 设置按钮内边距
                textStyle: TextStyle(fontSize: 16), // 设置按钮文本样式
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8), // 设置按钮圆角
                ),
              ),
            ),

          ],
        ),
      )
    );
  }
}

/// The details screen
class DetailsScreen extends StatelessWidget {
  /// Constructs a [DetailsScreen]
  const DetailsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Details Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () => context.go('/'),
          child: const Text('Go back to the Home screen'),
        ),
      ),
    );
  }
}

class LogingPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Loging'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 账号输入框
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: TextField(
                decoration: InputDecoration(
                  labelText: 'Username',
                ),
              ),
            ),
            SizedBox(height: 16),
            // 密码输入框
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: TextField(
                obscureText: true,
                decoration: InputDecoration(
                  labelText: 'Password',
                ),
              ),
            ),
            SizedBox(height: 24),
            // 登录按钮
            ElevatedButton(
              onPressed: () {
                // 处理登录逻辑
                // ...
              },
              //child: Text('Login'),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("loging"),
              Padding(padding: EdgeInsets.only(top: 30.0)),
              ElevatedButton(
                onPressed: () => context.go("/"),

                child: Text('Go to the start'),
                style: ElevatedButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.amber,
                ),
              )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

 让我来分析一下代码

创建了一个GoRouter实例_router,用于配置应用程序的路由信息。

final GoRouter _router = GoRouter(
  routes: <RouteBase>[
    GoRoute(
      path: '/',
      builder: (BuildContext context, GoRouterState state) {
        return const HomeScreen();
      },
      routes: <RouteBase>[
        GoRoute(
          path: 'details',
          builder: (BuildContext context, GoRouterState state) {
            return const DetailsScreen();
          },
        ),
        GoRoute(
            path: "loging",
            builder: (BuildContext context, GoRouterState state){
              return  LogingPage();
            }
        ),
      ],



    ),
  ],
);

这段代码扩展了原始路由配置,使得应用程序具有三个路由:

  • 根路由'/',映射到HomeScreen小部件。
  • 子路由'details',映射到DetailsScreen小部件。
  • 子路由'loging',映射到LogingPage小部件。

这样,当应用程序导航到'/details'路径时,将显示DetailsScreen小部件;导航到'/loging'路径时,将显示LogingPage小部件。

那要怎么跳转呢
 

children: [
            ElevatedButton(
              onPressed: () => context.go("/details"),
              child: Text('Go to the Details screen'),
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white,  // 设置按钮文本颜色为白色
                backgroundColor: Colors.blue, // 设置按钮背景为蓝色
                padding: EdgeInsets.symmetric(vertical: 16, horizontal: 24), // 设置按钮内边距
                textStyle: TextStyle(fontSize: 16), // 设置按钮文本样式
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8), // 设置按钮圆角
                ),
              ),
            ),
            ElevatedButton(
              onPressed: () => context.go("/loging"),
              child: Text('Go to the LoginPage'),
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white, // 设置按钮文本颜色为白色
                backgroundColor: Colors.green, // 设置按钮背景为绿色
                padding: EdgeInsets.symmetric(vertical: 16, horizontal: 24), // 设置按钮内边距
                textStyle: TextStyle(fontSize: 16), // 设置按钮文本样式
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8), // 设置按钮圆角
                ),
              ),
            ),

          ],

 利用ElevatedButton 控件进行跳转,

onPressed: () => context.go("/loging"),  //里面填写的是路由的路径名称

看看效果图

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
当使用 Flutter 的 go_router 进行进阶使用时,您可以探索以下功能和技巧: 1. 命名路由:除了使用路径来导航页面,go_router 还支持命名路由,通过给每个路由规则指定一个唯一的名称,可以更方便地进行页面跳转。例如: ```dart final routes = [ GoRoute( path: '/', pageBuilder: (context, state) => HomePage(), name: 'home', ), GoRoute( path: '/details/:id', pageBuilder: (context, state) => DetailsPage(id: state.params['id']), name: 'details', ), ]; ``` 然后,您可以通过名称进行页面跳转: ```dart GoRouter.of(context).goNamed('details', params: {'id': '123'}); ``` 2. 参数传递:go_router 允许您在页面之间传递参数。在路由规则中,可以定义参数占位符,然后在页面构建器中获取这些参数并使用它们。例如: ```dart final routes = [ GoRoute( path: '/details/:id', pageBuilder: (context, state) => DetailsPage(id: state.params['id']), ), ]; ``` 在 DetailsPage 中可以通过 `widget.id` 访问传递的参数。 3. 路由拦截和重定向:go_router 允许您在路由跳转之前进行拦截和处理。您可以使用 `beforeEnter` 方法来拦截特定的路由,并根据需要执行操作,例如权限验证、参数校验等。还可以使用 `redirectTo` 方法来重定向到其他路由。例如: ```dart final routes = [ GoRoute( path: '/details/:id', pageBuilder: (context, state) => DetailsPage(id: state.params['id']), beforeEnter: (context, state) { // 进行权限验证或其他操作 if (!isLoggedIn) { return redirectTo('/login'); } return null; }, ), ]; ``` 4. 页面切换动画:go_router 支持自定义页面切换动画,您可以为每个路由规则定义不同的动画效果。使用 `transitionDuration` 和 `transitionBuilder` 属性来自定义页面切换动画。例如: ```dart final routes = [ GoRoute( path: '/', pageBuilder: (context, state) => HomePage(), transitionDuration: Duration(milliseconds: 500), transitionBuilder: (context, animation, secondaryAnimation, child) { return FadeTransition(opacity: animation, child: child); }, ), ]; ``` 在上述示例中,我们使用了一个渐变的动画效果。 这些是 go_router 的一些进阶使用方法,您可以根据您的实际需求来灵活使用它们。请参考 go_router 的官方文档以获取更多详细信息和示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wniuniu_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值