flutter 为路由指定字符串值

s5a0g9ez  于 2023-06-07  发布在  Flutter
关注(0)|答案(1)|浏览(185)

我想显示一些项目作为一个网格和网格项目应该是可点击的,但我有路由问题。我怎样才能把每一个项目路由到它唯一的名称,例如aa,bb,cc。正如你在测试类中看到的,我可以写Navigator.pushNamed(context, Routes.aa);,但它所做的是,所有的项目都被路由到aa。
项目列表:

List Fin = [
["aa", "Resources/Images/test/aa.png"],
["bb", "Resources/Images/test/bb.png"],
["cc", "Resources/Images/test/cc.png"],];

GridView代码:

GridView.builder(
        physics: const ScrollPhysics(),
        shrinkWrap: true,
        itemCount: Fin.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10),
        itemBuilder: (context, index) {
          return Test(
            title: Fin[index][0],
            icon: Fin[index][1],
          );
        },
      ),

测试类别:

return InkWell(
  onTap: () {
    Navigator.pushNamed(context, Routes.NeedSeparateRouteForEachItem);
  },
  child: Container(
    decoration: BoxDecoration(
      color: Colors.green,
      borderRadius: BorderRadius.circular(20),
    ),
  ),
);
nx7onnlm

nx7onnlm1#

您需要进行两个小更改:
1.在您的测试类中:

InkWell(
  onTap: () {
    context.pushNamed(Routes.item,pathParameters: {'item': title});
  },
  child: Container(
    decoration: BoxDecoration(
      color: Colors.green,
      borderRadius: BorderRadius.circular(20),
    ),
  ),
)

1.在GoRouter中

GoRouter(
  initialLocation: '/',
  routes: [
    GoRoute(
      path: Routes.item.path+':item',
      name: Routes.item.name,
      pageBuilder: (ctx, state) {
        return const MaterialPage(
          child: ItemPage(title: state.pathParameters['item']),
        );
      },
    ),
  ],
)

其中Routes的定义为

class Routes{
  static final RouteDetails item = RouteDetails('details','/detail');
}
class RouteDetails {
  RouteDetails(this.name, this.path);
  final String name;
  final String path;
}

相关问题