flutterbuild-runnerauto-route

Flutter auto_route issue with super.key property


auto_route: ^8.1.3 auto_route_generator: ^8.0.0 build_runner: ^2.4.11

Could someone point me how to exclude "key" argument from build_runner. I try to create route with single required argument - storyName


@RoutePage()
class StoryView extends StatefulWidget {
  const StoryView({super.key, @pathParam required this.storyName});

  final String storyName;

  @override
  State<StoryView> createState() => _StoryViewState();
}

but after run - flutter packages pub run build_runner watch. Build runner create file auto_router.gr.dart with error: Undefined class 'Key'. Try changing the name to the name of an existing class, or creating a class with the name 'Key'

/// generated route for
/// [StoryView]
class StoryRoute extends PageRouteInfo<StoryRouteArgs> {
  StoryRoute({
    Key? key,
    required String storyName,
    List<PageRouteInfo>? children,
  }) : super(
          StoryRoute.name,
          args: StoryRouteArgs(
            key: key,
            storyName: storyName,
          ),
          rawPathParams: {'storyName': storyName},
          initialChildren: children,
        );

  static const String name = 'StoryRoute';

  static const PageInfo<StoryRouteArgs> page = PageInfo<StoryRouteArgs>(name);
}

My routes:

import 'package:auto_route/auto_route.dart';
import 'package:seawolves/src/presentation/views/views.dart';

part 'app_router.gr.dart';

@AutoRouterConfig(replaceInRouteName: 'View,Route')
class AppRouter extends _$AppRouter {
  @override
  List<AutoRoute> get routes => [
        AutoRoute(path: '/', page: WrapperRoute.page, initial: true, children: [
          RedirectRoute(path: '', redirectTo: 'home'),
          AutoRoute(path: 'home', page: HomeRoute.page),
          AutoRoute(path: 'history', page: HistoryRoute.page),
          AutoRoute(path: 'toolkit', page: ToolkitRoute.page),
          AutoRoute(path: 'story/:storyName', page: StoryRoute.page),
        ]),
      ];
}

Routes without any arguments have no problems with key...


Solution

  • The cause of that issue is that auto_router.gr.dart is part of your auto_router.dart file which is the one that hosts all the imports. Also the Flutter one. For the Key type you need to import package:flutter/foundation.dart (or material/cupertino) in that auto_router.dart file.

    Currently, it's impossible to customize in the auto_route_generator whether the key parameter is skipped.