flutter 已添加GetMaterialApp,在showErrorSnackBar上显示错误

wkyowqbh  于 2023-05-01  发布在  Flutter
关注(0)|答案(1)|浏览(324)

我已经在我的main.dart中添加了我的GetMaterialApp,但我在我的common.dart中出现错误。错误是_CastError (Null check operator used on a null value)在第3行。heading具有null值,在error!中显示:

"You are trying to use contextless navigation without
      a GetMaterialApp or Get.key.
      If you are testing your app, you can use:
      [Get.testMode = true], or if you are running your app on
      a physical device or emulator, you must exchange your [MaterialApp]
      for a [GetMaterialApp].
      "

common.dart

static void showErrorSnackBar(String? error,
      {bool instantInit = true, String? heading}) {
    Get.snackbar(heading ?? "Error", error!, // line 3
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.redAccent,
        instantInit: instantInit,
        margin: const EdgeInsets.only(bottom: 10, left: 10, right: 10));
  }

在我的main.dart中,我使用flutter_background_services每15分钟获取当前位置的更新。我就是这么做的

Future<void> onStart(ServiceInstance service) async {
  // Only available for flutter 3.0.0 and later
  DartPluginRegistrant.ensureInitialized();
  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });

    service.on('setAsBackground').listen((event) {
      service.setAsBackgroundService();
    });
  }
  service.on('stopService').listen((event) {
    service.stopSelf();
  });
  timer = Timer.periodic(const Duration(seconds: 15), (timer) async {
    await control();
    print("executed at line 180");
    service.on('stopService').listen((event) {
      service.stopSelf();
      if (timer.isActive) {
        timer.cancel();
      }
    });
  });
  print('Flutter Background Service : ${DateTime.now()}');
}

在我的control()是我ping我的位置。

control() async {
  await lC.pingLocation(); //get current location
}

在我的pingLocation()中,这是我得到位置的地方。它每15秒ping一次,以检查用户是否在2公里内。如果是,则它ping并不执行任何操作。如果它在接下来的15秒内ping,并检查用户不在2公里内,那么我需要显示我在common.dart中显示的showErrorSnackBar。所以我包含了try{} catch{e},以显示用户超出范围(不在2km内)时的错误。所以我把模拟器的位置改到了2公里外的某个地方,catch(e)被抓住了。它执行了Utils.showErrorSnackBar(e.toString());,这就是我得到错误_CastError (Null check operator used on a null value)的原因,我怀疑这是You are trying to use contextless navigation without a GetMaterialApp or Get.key.的原因。
public void run()

pingLocation() async {
    // var isRunning = await service.isRunning();
    try {
      await _getCurrentPosition();
      print('is called');
      print(DateTime.now().toString());
      if (response.success! && response.fullResponse != null) {
        final responseData = response.fullResponse.data;
        if (responseData != null && responseData != 0) {
if(responseData.toString() == "[]"){
Get.offAllNamed(AppRoutes.home); //Cause of the error as well!
}
          }
    } catch (e) {
      Utils.showErrorSnackBar(e.toString()); //error
    }
  }

另一个附带说明,当我不在main中使用pingLocation()时。dart,错误不会发生。有什么建议吗?
谁想看我的main.dartGetMaterialApp

@override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      supportedLocales: const [
        Locale('en', 'IN'),
        Locale('en', 'US'),
      ],
      debugShowCheckedModeBanner: false,
      getPages: AppPages.all,
      initialRoute: PrefData().readString('isLogin') == 'true'
          ? AppRoutes.home
          : AppRoutes.login,
      enableLog: true,
      navigatorKey: Get.key,
      locale: const Locale('en', 'US'),
    );
  }

更新!
Get.offAllNamed(AppRoutes.home)也是错误的原因。有什么建议吗?

fcwjkofz

fcwjkofz1#

GetMaterialApp替换MaterialApp。就像这样

GetMaterialApp(
          debugShowCheckedModeBanner: false,
          themeMode: ThemeMode.system,
          home: HomePage(),
        )

相反

MaterialApp(
          debugShowCheckedModeBanner: false,
          themeMode: ThemeMode.system,
          title: 'Gst invoice and billing',
          home: HomePage(),
        )

相关问题