i6x86
i6x86

Reputation: 1627

Null check operator used on a null value when use Get.offAll()

I have this AuthController that extends GetxController. I have a worker that trigger a function when the firebase user state change:

  _user.bindStream(auth.userChanges());
    ever(_user, _initialScreen);

Then in _initialScreen I have this code:

 _initialScreen(User? user) {
    if (user != null) {
      Get.offAll(() =>  WelcomePage(email: user.email!));
    } else {
      Get.offAll(() => LoginPage());
    }
  }

The problem is that it gives me "Null check operator used on a null value" error, but if I use

Get.to(LoginPage());

instead of

Get.offAll(() => LoginPage());

the bug disappears. Can anyone explain why this happens, please?

EDIT: Just in case here is my main.dart:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp().then((value) => Get.put(AuthController()));
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(

      home: Builder(builder: (BuildContext context) {
        ScreenUtil.init(
            BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width,
                maxHeight: MediaQuery.of(context).size.height),
            designSize: const Size(360, 690),
            context: context,
            minTextAdapt: true,
            orientation: Orientation.portrait);
        return SplashScreen();
      },)
    );}
}

EDIT 2: I'm posting AuthController.dart too:

class AuthController extends GetxController {
  static AuthController instance = Get.find();
  late Rx<User?> _user;
  FirebaseAuth auth = FirebaseAuth.instance;

  @override
  void onReady() {
    super.onReady();
    _user = Rx<User?>(auth.currentUser);

    //Si hay cambios nuestro usuario estará notificado
    _user.bindStream(auth.userChanges());
    ever(_user, _initialScreen);
  }

  _initialScreen(User? user) {
    if (user != null) {
      Get.offAll(() =>  WelcomePage(email: user.email!));

    } else {
      print('Welcome Page');
      Get.to(LoginPage());
    }
  }

  void register(String email, password) async {
    try {
      await auth.createUserWithEmailAndPassword(email: email.trim(), password: password);
    } catch(e) {
      Get.snackbar('Error', 'Algo ha fallado',
      backgroundColor: Colors.lightGreen,
      snackPosition: SnackPosition.BOTTOM,
        titleText: const Text(
          'El registro de usuario ha fallado',
          style: TextStyle(
            color: Colors.black
          ),
        ),
        messageText: Text(
          e.toString(),
            style: const TextStyle(
                color: Colors.black
            )
        )
      );
    }
  }

  void login (String email, password) async {
    try {
      await auth.signInWithEmailAndPassword(email: email, password: password);
    } catch(e) {
      Get.snackbar('Error', 'Algo ha fallado',
          backgroundColor: Colors.lightGreen,
          snackPosition: SnackPosition.BOTTOM,
          titleText: const Text(
            'La identificación ha fallado',
            style: TextStyle(
                color: Colors.black
            ),
          ),
          messageText: Text(
              e.toString(),
              style: const TextStyle(
                  color: Colors.black
              )
          )
      );
    }
  }

  void logOut() async {
    await auth.signOut();
  }
}

EDIT 3: Providing StackTrace.

Performing hot restart... Syncing files to device motorola one fusion... Restarted application in 1.476ms. I/flutter (32446): Auth en main User(displayName: , email: [email protected], emailVerified: true, isAnonymous: false, metadata: UserMetadata(creationTime: 2022-03-02 20:10:35.002, lastSignInTime: 2022-03-04 06:27:24.770), phoneNumber: , photoURL: null, providerData, [UserInfo(displayName: , email: [email protected], phoneNumber: , photoURL: null, providerId: password, uid: [email protected])], refreshToken: , tenantId: null, uid: 9QUP1DFa3I5Odash56HmOG7f7ZGTEfdsxpFD2) [GETX] Instance "AuthController" has been created [GETX] Instance "AuthController" has been initialized [GETX] Instance "GetMaterialController" has been created [GETX] Instance "GetMaterialController" has been initialized I/flutter (32446): AuthController en onReady User(displayName: , email: [email protected], emailVerified: true, isAnonymous: false, metadata: UserMetadata(creationTime: 2022-03-02 20:10:35.002, lastSignInTime: 2022-03-04 06:27:24.770), phoneNumber: , photoURL: null, providerData, [UserInfo(displayName: , email: [email protected], phoneNumber: , photoURL: null, providerId: password, uid: [email protected])], refreshToken: , tenantId: null, uid: 9QUP1DFIfsfdfe5O3h56HmOG7f7Z7GTE7pFD2) [GETX] GOING TO ROUTE /WelcomePage [GETX] REMOVING ROUTE /

======== Exception caught by widgets library ======================================================= The following _CastError was thrown building WelcomePage(dirty): Null check operator used on a null value

The relevant error-causing widget was: WelcomePage WelcomePage:file:///Users/user/AndroidStudioProjects/prjname/lib/core/services/auth_controller.dart:28:25 When the exception was thrown, this was the stack: #0 Element.widget (package:flutter/src/widgets/framework.dart:3203:31) #1 StatelessElement.widget (package:flutter/src/widgets/framework.dart:4824:39) #2 debugCheckHasMediaQuery. (package:flutter/src/widgets/debug.dart:229:17) #3 debugCheckHasMediaQuery (package:flutter/src/widgets/debug.dart:245:4) #4 MediaQuery.of (package:flutter/src/widgets/media_query.dart:859:12) #5 ScreenUtil.screenHeight (package:flutter_screenutil/screen_util.dart:74:36) #6 WelcomePage.build (package:paclage_/ui/views/welcome_page.dart:15:53) #7 StatelessElement.build (package:flutter/src/widgets/framework.dart:4827:28) #8 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4754:15) #9 Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5) #10 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2659:19) #11 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21) #12 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5) #13 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15) #14 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1081:9) #15 SchedulerBinding.scheduleWarmUpFrame. (package:flutter/src/scheduler/binding.dart:862:7) (elided 4 frames from class _RawReceivePortImpl, class _Timer, and dart:async-patch)

Edit 4: The WelcomePage:file:///Users/user/AndroidStudioProjects/prjname/lib/core/services/auth_controller.dart:28:25 line is this:

Get.offAll(() => WelcomePage(email: user.email!));

Upvotes: 3

Views: 1078

Answers (2)

Sayed Main Uddin
Sayed Main Uddin

Reputation: 34

Suppose you are Navigating to DashBoard from Login page. Now use bellow code into your Dashboard page.

  @override
  Widget build(BuildContext context) {
    Get.lazyPut(()=>DashBoardController());
....

Upvotes: 0

Mehedi Hasan
Mehedi Hasan

Reputation: 95

I encountered the same issue recently. I was using a RouteHelper class to manage the Routes in my app.

I created an async function Binding the dependencies like Controllers and Repositories with GetxControllers and GetService. I called this function in the main function of my Flutter app.

I implemented Get.offNamed() while logging in and also while logging out. And after logging out if I tried to log in immediately without closing the app it gave the same error.

The error occurred due to a missing Controller that was supposed to be loaded before going to my Landing Screen.

So, I implemented:

Get.lazyPut(() => LandingScreenController());

in an appropriate place of my code again before returning or building the widget where an instance of my LandingScreenController is used. And it solved my problem.

Upvotes: 0

Related Questions