Home > database >  getx problem when initiating auth controller before GetMaterialApp and trying to navigate to named r
getx problem when initiating auth controller before GetMaterialApp and trying to navigate to named r

Time:09-05

Trying to do the following, using getx:

  • Get.put the auth controller (listening to auth change)
  • creating a GetMaterialApp
  • upon auth change, navigating to a named route '/login'

Here's a sample code:

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

  // firebase init
  await Firebase.initializeApp();

  // controllers
  Get.put<AuthController>(AuthController());

  runApp(
    MyApp(),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Get',
      initialRoute: "/",
      routes: appRoutes,
    );
  }
}

Trying to do so results in the following error:

You are trying to use contextless navigation without a GetMaterialApp or Get.key

and that's because the onAuthChanged event is called before the GetMaterialApp is created/initiated, I guess...

How can I create and initiate auth controller on my main class?

CodePudding user response:

Remove the Get.put statement on your main function block, then

Try this

@override
  Widget build(BuildContext context) {
    // Add this line
    Get.put<AuthController>(AuthController(), permanent: true,);
    return GetMaterialApp(
      title: 'Get',
      initialRoute: "/",
      routes: appRoutes,
    );
  }

or

@override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Get',
      initialRoute: "/",
      routes: appRoutes,
      // add this argument
      onInit: () {
        Get.put<AuthController>(AuthController(), permanent: true,);
      },
    );
  }
  • Related