jonataslaw / getx

Open screens/snackbars/dialogs/bottomSheets without context, manage states and inject dependencies easily with Get.
MIT License
10.34k stars 1.62k forks source link

Null check operator used on a null value #1691

Closed Blast06 closed 3 years ago

Blast06 commented 3 years ago

Describe the bug It throws a null error at the start of running the project

Reproduction code NOTE: THIS IS MANDATORY, IF YOUR ISSUE DOES NOT CONTAIN IT, IT WILL BE CLOSED PRELIMINARY)

//get_state.dart

if (widget.global) {
      if (isRegistered) {
        if (GetInstance().isPrepared<T>(tag: widget.tag)) {
          _isCreator = true;
        } else {
          _isCreator = false;
        }
        controller = GetInstance().find<T>(tag: widget.tag);
      } else {
        controller = widget.init;
        _isCreator = true;
        GetInstance().put<T>(controller!, tag: widget.tag);
      }
    } else {
      controller = widget.init;
      _isCreator = true;
      controller?.onStart();
    }

To Reproduce Steps to reproduce the behavior:

  1. On get: 4.2.5
  2. run a project
  3. See error

Expected behavior It should not throw a null error at the start of running the project

Screenshots image

Flutter Version: 2.3.0-24.1.pre

Getx Version: 4.2.5

Describe on which device you found the bug: Any device

Minimal reproduce code

//main.dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;

  await MobileAds.initialize(
    bannerAdUnitId: MyAdmob.getBannerAdId(),
    interstitialAdUnitId: MyAdmob.getInterstitialAdId(),
    appOpenAdUnitId: MyAdmob.getOpenAdId(),
  );
  await MobileAds.requestTrackingAuthorization();

  Get.put(AdmobController());
  // FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
  // Admob.requestTrackingAuthorization();
  //
  // SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
  //   systemNavigationBarColor: Colors.greenAccent,
  // ));
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  // Locale myLocale;

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'appname',
      debugShowCheckedModeBanner: false,
      theme: appThemeData,
      // translations: MyTransalations(),
      // locale: Get.deviceLocale,
      // initialRoute: Routes.HOME_PAGE,
      home: SplashPage(),
      // locale: Get.deviceLocale,
      // translations: MyTransalations(),
    );
  }
}
//splas_page.dart
class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  final sp = Get.put(SplashController());
  // RiveAnimationController _controller;
  @override
  void initState() {
    super.initState();
    // _controller = SimpleAnimation('idle', autoplay: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            const Expanded(
              /// Para fines practicos usarremos esta animacion
              /// disponible en linea.
              child: RiveAnimation.asset(
                'assets/splash.riv',
                fit: BoxFit.cover,
              ),
            ),
            Text(
              'loading_txt'.tr,
              style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
            )
          ],
        ),
      ),
    );
  }
}
//home_page.dart

class HomePage extends StatelessWidget {
  // const HomePage({Key? key}) : super(key: key);
  final TextEditingController nameController = TextEditingController();
  var logger = Logger();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('videos'),
      ),
      body: Container(
        decoration: const BoxDecoration(color: Colors.amberAccent),
        child: Padding(
          padding: const EdgeInsets.only(top: 50),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            // mainAxisAlignment: MainAxisAlignment.,
            children: <Widget>[
              const SizedBox(
                height: 30,
              ),
              const Text('Introducir nombre'),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: GetBuilder<HomeController>(
                  builder: (_) => TextField(
                    controller: nameController,
                    decoration: InputDecoration(hintText: 'video_url'.tr),
                  ),
                ),
              ),
              GetBuilder<HomeController>(
                builder: (_) => ElevatedButton(
                  onPressed: () {
                    if (nameController.text.isEmpty) {
                      logger.v("lenght of text: ${nameController.text.length}");
                      nameController.clear();
                      // return null;
                    }

                    // _.getLink(nameController.text);
                    // logger.v(nameController.text);
                  },
                  child: Text('download_btn'.tr),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
jonataslaw commented 3 years ago

Initialize HomeController, and it will work

Hasib74 commented 3 years ago

Same issue here. I can not run the app after updating the package version.

Hasib74 commented 3 years ago

When I run the app on getx 4.3.0 then it's showing an error. But if I run on an older version then it works perfectly.

Null check operator used on a null value
The relevant error-causing widget was: 
  Directionality file:///home/monu/FlutterSdk/flutter_updated/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.3.0/lib/get_navigation/src/root/get_material_app.dart:217:12
When the exception was thrown, this was the stack: 
#0      PageRedirect.page (package:get/get_navigation/src/routes/route_middleware.dart:199:50)
#1      GetMaterialApp.initialRoutesGenerate (package:get/get_navigation/src/root/get_material_app.dart:212:9)
#2      _WidgetsAppState.build.<anonymous closure> (package:flutter/src/widgets/app.dart:1533:51)
#3      NavigatorState.restoreState (package:flutter/src/widgets/navigator.dart:3439:41)
#4      RestorationMixin._doRestore (package:flutter/src/widgets/restoration.dart:984:5)
danieljimeneznz commented 3 years ago

@Hasib74 I'm facing that same issue that you have faced, It has the same signature but I don't think it's related to the bug that @Blast06 originally opened.

I know the bug is from the following line:

 final _r = (isUnknown ? unknownRoute : route)!;

The line fails because unknownRoute and route are null (it appears that on application start route does not have a value, @jonataslaw might be able to shed some light as to why this might occur), and thus the null check operator throws. To fix this you can just ensure that unknownRoute is defined in the GetMaterialApp. i.e. you can use your the first route in the route object as the unknownRoute.

GetMaterialApp(
  routes: routes,
  unknownRoute: routes[0]
);
jonataslaw commented 3 years ago

Well, I'm closing this issue because it has become a compilation of attention errors. The initial issue was caused by the lack of controller initialization. Now I'm seeing null-exception reports from people who haven't set initialRoute. Please make sure you are facing a bug before opening an issue, look at the project and check if everything is ok. When you open an issue for lack of attention, you occupy my time that could be spent on a possible real issue.

jonataslaw commented 3 years ago

@Hasib74 I'm facing that same issue that you have faced, It has the same signature but I don't think it's related to the bug that @Blast06 originally opened.

I know the bug is from the following line:

 final _r = (isUnknown ? unknownRoute : route)!;

The line fails because unknownRoute and route are null (it appears that on application start route does not have a value, @jonataslaw might be able to shed some light as to why this might occur), and thus the null check operator throws. To fix this you can just ensure that unknownRoute is defined in the GetMaterialApp. i.e. you can use your the first route in the route object as the unknownRoute.

GetMaterialApp(
  routes: routes,
  unknownRoute: routes[0]
);

You should use getPages, not routes, please follow the documentation. You need set initialRoute too

danieljimeneznz commented 3 years ago

@Hasib74 I'm facing that same issue that you have faced, It has the same signature but I don't think it's related to the bug that @Blast06 originally opened. I know the bug is from the following line:

 final _r = (isUnknown ? unknownRoute : route)!;

The line fails because unknownRoute and route are null (it appears that on application start route does not have a value, @jonataslaw might be able to shed some light as to why this might occur), and thus the null check operator throws. To fix this you can just ensure that unknownRoute is defined in the GetMaterialApp. i.e. you can use your the first route in the route object as the unknownRoute.

GetMaterialApp(
  routes: routes,
  unknownRoute: routes[0]
);

You should use getPages, not routes, please follow the documentation. You need set initialRoute too

@jonataslaw Apologies my comment was mityped, I have all of these set, however anytime I try to route it always sends me to the unknownRoute? and if I don't have unknownRoute I get the null error...

        initialRoute: HomeScreen.pageId,
        getPages: routes,
        unknownRoute: routes[0],

Worked in 4.1.4 but broken up until 4.3.0

jonataslaw commented 3 years ago

How do you define your route? Are you sure you aren't missing slashes? This works well on my projects in production, so I need more details to know where the problem is.

danieljimeneznz commented 3 years ago

Ah I was missing slashes... Thanks for that!