Flutter路由管理插件go_router_prototype的使用

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

Flutter路由管理插件go_router_prototype的使用

GoRouter API原型。有关更多信息,请参阅设计文档

完整示例Demo

以下是一个完整的示例,展示了如何在Flutter应用中使用go_router_prototype插件进行路由管理。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerDelegate: AppRouterDelegate(),
      routeInformationParser: AppRouteInformationParser(),
    );
  }
}

class AppRouterDelegate extends RouterDelegate<AppRoutePath>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin<AppRoutePath> {
  [@override](/user/override)
  AppRoutePath get currentConfiguration {
    // 根据当前路由返回不同的路径对象
    if (_currentLocation == '/') {
      return AppRoutePath.home();
    } else if (_currentLocation == '/details') {
      return AppRoutePath.details();
    }
    return AppRoutePath.unknown();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 根据路径对象渲染不同的页面
    return Navigator(
      key: navigatorKey,
      pages: [
        if (_currentLocation == '/')
          MaterialPage(
            key: ValueKey('HomePage'),
            child: HomePage(),
          )
        else if (_currentLocation == '/details')
          MaterialPage(
            key: ValueKey('DetailsPage'),
            child: DetailsPage(),
          ),
      ],
      onPopPage: (route, result) {
        if (!route.didPop(result)) return false;
        _currentLocation = '/';
        notifyListeners();
        return true;
      },
    );
  }

  [@override](/user/override)
  Future<void> setNewRoutePath(AppRoutePath path) async {
    if (path.isUnknown || path.isHome) {
      _currentLocation = '/';
    } else if (path.isDetails) {
      _currentLocation = '/details';
    }
  }
}

class AppRouteInformationParser extends RouteInformationParser<AppRoutePath> {
  [@override](/user/override)
  Future<AppRoutePath> parseRouteInformation(RouteInformation routeInformation) {
    final uri = Uri.parse(routeInformation.location ?? '/');
    if (uri.pathSegments.isEmpty) {
      return SynchronousFuture(AppRoutePath.home());
    } else if (uri.pathSegments.length == 1 && uri.pathSegments.first == 'details') {
      return SynchronousFuture(AppRoutePath.details());
    }
    return SynchronousFuture(AppRoutePath.unknown());
  }

  [@override](/user/override)
  RouteInformation restoreRouteInformation(AppRoutePath path) {
    if (path.isUnknown) {
      return RouteInformation(location: '/');
    } else if (path.isHome) {
      return RouteInformation(location: '/');
    } else if (path.isDetails) {
      return RouteInformation(location: '/details');
    }
    return RouteInformation(location: '/');
  }
}

class AppRoutePath {
  final String location;

  const AppRoutePath.home() : location = '/';
  const AppRoutePath.details() : location = '/details';
  const AppRoutePath.unknown() : location = '*';

  bool get isHome => location == '/';
  bool get isDetails => location == '/details';
  bool get isUnknown => location == '*';
}

class HomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('首页')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // 导航到详情页面
            GoRouter.of(context).go('/details');
          },
          child: Text('进入详情页'),
        ),
      ),
    );
  }
}

class DetailsPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('详情页')),
      body: Center(child: Text('这是详情页')),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用go_router_prototype插件进行路由管理的示例代码。请注意,go_router_prototype是一个假设的插件名称,用于演示目的。实际使用中,你可能需要参考具体的插件文档,例如go_router或其他路由管理插件。不过,我会基于常见的路由管理插件的使用方式来编写示例代码。

假设我们有一个Flutter项目,并且决定使用go_router_prototype(这里我们假设它与go_router有相似的API)进行路由管理。

1. 添加依赖

首先,在pubspec.yaml文件中添加go_router_prototype依赖(注意:这里使用go_router作为示例,因为go_router_prototype是一个假设的插件):

dependencies:
  flutter:
    sdk: flutter
  go_router: ^x.y.z  # 替换为实际版本号

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

2. 配置路由

接下来,我们配置路由。通常,这在一个单独的文件中完成,例如app_router.dart

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

final GoRouter router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const HomeScreen(),
      routes: [
        GoRoute(
          path: 'details/:id',
          builder: (context, state) {
            final id = state.params['id']!;
            return DetailsScreen(id: id);
          },
        ),
      ],
    ),
  ],
  redirect: (context, state) {
    final currentPath = state.location!;

    if (currentPath == '/') {
      return '/details/1'; // 默认重定向到详情页
    }

    return null; // 没有重定向
  },
);

3. 使用MaterialApp

main.dart中,我们使用MaterialApp.router来应用路由配置:

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

void main() {
  runApp(MaterialApp.router(
    routerDelegate: router.routerDelegate,
    routeInformationParser: router.routeInformationParser,
    title: 'Flutter GoRouter Demo',
  ));
}

4. 创建屏幕组件

创建两个屏幕组件:HomeScreenDetailsScreen

HomeScreen.dart

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

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

  @override
  Widget build(BuildContext context) {
    final context = useGoRouter();

    return Scaffold(
      appBar: AppBar(title: Text('Home')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            context.go('/details/1');
          },
          child: Text('Go to Details'),
        ),
      ),
    );
  }
}

DetailsScreen.dart

import 'package:flutter/material.dart';

class DetailsScreen extends StatelessWidget {
  final String id;

  const DetailsScreen({Key? key, required this.id}) : super(key: key);

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

5. 运行应用

现在,你可以运行你的Flutter应用。你应该能够看到一个主页,点击按钮后会导航到详情页,并且详情页会显示传递的ID。

请注意,上述代码是一个简化的示例,用于演示如何使用路由管理插件进行基本的路由配置和导航。实际项目中,你可能需要根据具体需求进行更多的配置和自定义。

回到顶部