flutter go

马肤
这是懒羊羊
1 项目中添加最新的依赖
go_router: ^13.1.0

如下图所示,我当前使用的flutter版本为3.16.0

flutter go,在这里插入图片描述,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,操作,使用,应用,第1张

然后修改应用的入口函数如下:

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: _router,
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
    );
    // return MaterialApp(
    //   title: 'Flutter Demo',
    //   theme: ThemeData(
    //     colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
    //     useMaterial3: true,
    //   ),
    //   home:  MyHomePage(),
    // );
  }
}

其实就是将原来的入口 MaterialApp 使用 MaterialApp.router 替换了,参数 routerConfig 就是配置的所有的路由页面,比如我这里的配置如下:

final GoRouter _router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (BuildContext context, GoRouterState state) {
        return MyHomePage();
      },
      routes: [
        GoRoute(
          path: 'two',
          builder: (BuildContext context, GoRouterState state) {
            return TwoPage();
          },
        ),
      ],
    ),
  ],
);

“/” 配置的就是加载的默认的启动的首页面,然后我这里面相当于是配置了两个基本的页面。

2 实现基本的页面交互

在页面MyHomePage放一个按钮,点击按钮打开 TwoPage 第二个页面,打开页面的核心代码如下:

使用 Navigator 正常操作如下“

    Navigator.of(context)
        .push(MaterialPageRoute(builder: (BuildContext context) {
      return TwoPage();
    }));

使用 go_router 操作如下:

context.go("/two");

然后在页面 TwoPage 中点击按钮返回上一个页面​:

使用 Navigator 正常操作如下:

 Navigator.of(context).pop();

​用 go_router 操作如下:

context.pop();
3 页面跳转传参数

基本简单参数传递,比如一个 userId,页面路由定义如下:ThreePage就是我定义的目标页面,它需要一个参数 userId。

GoRoute(
    path: 'three/:userId',
    builder: (BuildContext context, GoRouterState state) {
      // 使用 state.params 获取路由参数的值
      final userId = (state.pathParameters['userId']!);
      return ThreePage(userId:userId);
    },
  ),

点击一个按钮跳转目标页面,我这里传的参数 userId的值为 123

context.go("/three/123");

复杂传参数 请看后续


文章版权声明:除非注明,否则均为VPS857原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复:表情:
评论列表 (暂无评论,0人围观)

还没有评论,来说两句吧...

目录[+]

取消
微信二维码
微信二维码
支付宝二维码