I cant transfer the next file using auto_route

36 Views Asked by At

My problem is the code of the router wont work I want to transfer from one screen or file to another using auto_route. My problem is routing in the menuItem and in the onPressed in the Positioned. When I tap it, it shows this error "AutoRouter operation requested with a context that does not include an AutoRouter"

      `Positioned(
            top: 40,
            left: 20,
            child: IconButton(
                icon: Icon(
                  Icons.info,
                  color: Colors.white,
                ),
                onPressed: () {
                  AutoRouter.of(context).push(Instruction() as PageRouteInfo);
                })),

        Positioned(
          top: size.height * 0.52,
          child: Container(
            height: MediaQuery.of(context).size.height * 0.5,
            width: MediaQuery.of(context).size.width,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Column(
                children: <Widget>[
                  Text(
                    'Menu',
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                      fontSize: 20,
                    ),
                  ),
                  Expanded(
                    child: GridView.count(
                      childAspectRatio: 1.5,
                      crossAxisCount: 2,
                      shrinkWrap: true,
                      crossAxisSpacing: 0,
                      children: [
                        Hero(
                          tag: 'humay',
                          child: MenuItem(

                            title: 'Humay',
                            assetName: 'assets/images/rice.svg',
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => const CalculatePage(
                                    plantEnum: PlantEnum.rice,
                                  ),
                                ),
                              );
                            },

                          ),
                        ),
                        MenuItem(
                          title: 'Mga datus',
                          assetName: 'assets/images/to-do-list.svg',
                          onTap: () {
                            AutoRouter.of(context).push(const SaveData());
                          },
                        ),
                        MenuItem(
                          title: 'Tempo',
                          assetName: 'assets/images/sunny.svg',
                          onTap: () {
                            context.router.push(const WeatherRoute());
                          },
                        ),
                        MenuItem(
                          title: 'Guidlines',
                          assetName: 'assets/images/guideline.svg',
                          onTap: () {

                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),`

////main.dart

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await initHive();

  await initSettings();
  //await initNotification();
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (_) => WeatherProvider()),
    ],
    child: MyApp(),
  ));
}

Future<void> initSettings() async {
  await Settings.init(
    cacheProvider: _isUsingHive ? HiveCache() : SharePreferenceCache(),
  );
}

bool _isUsingHive = true;

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    AppRouter appRouter = AppRouter();
    return MaterialApp(
        title: 'Mag-uuma',
        debugShowCheckedModeBanner: false,
       // onGenerateRoute: appRouter.AppRouter(),
        theme: ThemeData(
            primaryColor: const Color(0xFF00838f),
            visualDensity: VisualDensity.adaptivePlatformDensity,
            hintColor: Color(0xFFf50057),
            fontFamily: 'Poppins'),
        home: FutureBuilder(
          future: Future.wait([Hive.openBox<Farm>('farmBox')]),
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.error != null) {
                print(snapshot.error);
                return Scaffold(
                  body: Center(
                    child: Text('Something went wrong :/'),
                  ),
                );
              } else {
                return Navigator(
                  onGenerateRoute: (settings) {
                    return MaterialPageRoute(
                      builder: (context) => HomePage(),
                    );
                  },
                );
              }
            } else {
              return Scaffold(
                body: Center(
                  child: Text('Opening Hive...'),
                ),
              );
            }
          },
        )

    );
  }
}

My problem is the code of the router wont work I want to transfer from one screen or file to another using auto_route. My problem is routing in the menuItem and in the onPressed in the Positioned.

1

There are 1 best solutions below

0
rasityilmaz On

First of all,

If you are using auto_route your MaterialApp widget should look like this

 return MaterialApp.router(
          /// I have used the injectable package to inject the AppRouter class.
          routerConfig: locator<AppRouter>().config(),
          debugShowCheckedModeBanner: false,
          theme: regularTheme,
          darkTheme: darkTheme,
          themeMode: themeMode,
          localizationsDelegates: context.localizationDelegates,
          supportedLocales: context.supportedLocales,
          locale: context.locale,
        );

And that's it Example AppRouter class

@AutoRouterConfig()
class AppRouter extends _$AppRouter {
  @override
  List<AutoRoute> get routes => [

        AutoRoute(page: HomeViewRoute.page, initial: true),
     
      ];
}

You should mark the screen pages using annotations in this way and create the app_router_gr.dart class with auto_route_generator.

@RoutePage(name: 'HomeViewRoute')
final class HomeView extends StatelessWidget {

and lastly you can use this method now.

 /// Instruction should really be a PageRouteInfo you shouldn't change its type with 'as'
    AutoRouter.of(context).push(Instruction() as PageRouteInfo)

And remember, if you want to set the login screen asynchronously based on data, you should use RouteGuard.

final class AuthGuard extends AutoRouteGuard {
  factory AuthGuard() => instance;

  AuthGuard._internal();
  static final AuthGuard instance = AuthGuard._internal();

  @override
  Future<void> onNavigation(NavigationResolver resolver, StackRouter router) async {
    final farmBox = await Hive.openBox<Farm>('farmBox');

    ///
    /// I just want to show you an example
    /// You can edit thats part as you want
    ///
    if (farmBox.isEmpty) {
      router.push(SomeRoute());
    }

    //     Remember, if you want the routeguard to continue on its way, finish it with resolver.next().

    // You can develop a control mechanism for this, because if you tell RouteGuard to go the same way again, it will enter a loop, be careful.

    resolver.next();

   
  }
}

Example AppRouter after added RouteGuard

@AutoRouterConfig()
class AppRouter extends _$AppRouter {
  @override
  List<AutoRoute> get routes => [
     
        AutoRoute(
          page: HomeViewRoute.page,
          initial: true,
          guards: [AuthGuard()],
        ),
      
      ];
}