我尝试用 getter 解决问题,错误消息:
没有为“GoRouterState”类型定义 getter“params”。 尝试导入定义“params”的库,将名称更正为现有 getter 的名称,或者定义名为“params”的 getter 或字段。
我的 main.dart 代码如下所示:
GoRoute(
path: 'session/:level',
pageBuilder: (context, state) {
final levelNumber = int.parse(state.params['level']!);
final level = gameLevels
.singleWhere((e) => e.number == levelNumber);
return buildMyTransition<void>(
child: PlaySessionScreen(
level,
key: const Key('play session'),
),
color: context.watch<Palette>().backgroundPlaySession,
);
},
),
GoRouterState 在另一个文件中定义:
class ProductCategoryList extends StatelessWidget {
const ProductCategoryList({super.key});
@override
Widget build(BuildContext context) {
final GoRouterState state = GoRouterState.of(context);
final Category category = Category.values.firstWhere(
(Category value) => value.toString().contains(state.params['category']!),
orElse: () => Category.all,
);
final List<Widget> children = ProductsRepository.loadProducts(category: category)
.map<Widget>((Product p) => RowItem(product: p))
.toList();
return Scaffold(
backgroundColor: Styles.scaffoldBackground,
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: Text(getCategoryTitle(category), style: Styles.productListTitle),
backgroundColor: Styles.scaffoldAppBarBackground,
pinned: true,
),
SliverList(
delegate: SliverChildListDelegate(children),
),
],
),
);
}
}
版本 7.0.0 包含一些重大更改,包括
params
。
BuildContext 的namedLocation、pushNamed、pushReplacementNamed、replaceNamed 中的和params
已重命名为queryParams
和pathParameters
。queryParameters
对于您的情况,将会是
final levelNumber = int.parse(state.pathParameters['level']!); //better to do a null check
从版本10.0.0开始,
queryParameters
和queryParametersAll
也更新了。
要解决这个问题,您可以使用:
dart fix --apply
或手动更新:
来自:
Widget build(BuildContext context) {
final String location = GoRouterState.of(context).location;
final Map<String, String> queryParameters = GoRouterState.of(context).queryParameters;
final Map<String, List<String>> queryParametersAll = GoRouterState.of(context).queryParametersAll;
}
致:
Widget build(BuildContext context) {
final String location = GoRouterState.of(context).uri.toString();
final Map<String, String> queryParameters = GoRouterState.of(context).uri.queryParameters;
final Map<String, List<String>> queryParametersAll = GoRouterState.of(context).uri.queryParametersAll;
}