错误:flutter/lib/ui/ui_dart_state.cc(199) 未处理的异常:对空值使用空检查运算符

时间:2021-06-13 05:12:39

标签: flutter

我正在尝试通过可注入生成,我做了 flutter clean 也行不通,我使用的是稳定版 flutter 2.2.2,我在这行代码中遇到了空检查错误

此代码抛出错误

SharedPreferences.getInstance();

还有这个代码

   @module
    abstract class ThemeModule {
      @preResolve
      Future<SharedPreferences> get prefs async =>
           await SharedPreferences.getInstance();
    }

错误堆栈

E/flutter (27063): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (27063): #0      MethodChannel.binaryMessenger
package:flutter/…/services/platform_channel.dart:142
E/flutter (27063): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:148
E/flutter (27063): #2      MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:331
E/flutter (27063): #3      MethodChannel.invokeMapMethod
package:flutter/…/services/platform_channel.dart:358
E/flutter (27063): #4      MethodChannelSharedPreferencesStore.getAll
package:shared_preferences_platform_interface/method_channel_shared_preferences.dart:44
E/flutter (27063): #5      SharedPreferences._getSharedPreferencesMap
package:shared_preferences/shared_preferences.dart:180
E/flutter (27063): #6      SharedPreferences.getInstance
package:shared_preferences/shared_preferences.dart:56
E/flutter (27063): #7      main
package:financial/main.dart:12
E/flutter (27063): #8      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (27063): #9      _rootRun (dart:async/zone.dart:1354:13)
E/flutter (27063): #10     _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (27063): #11     _runZoned (dart:async/zone.dart:1789:10)
E/flutter (27063): #12     runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (27063): #13     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (27063): #14     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (27063): #15     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

3 个答案:

答案 0 :(得分:2)

我有同样的问题,解决方案是在运行应用程序之前在主函数中添加 WidgetsFlutterBinding.ensureInitialized()

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// init your dependency injection here
runApp(MyApp());}

来自docs

返回 WidgetsBinding 的一个实例,必要时创建并初始化它。如果创建了一个, 它将是一个 WidgetsFlutterBinding。如果之前已经初始化过,那么它至少会实现 WidgetsBinding。

只有在调用runApp之前需要初始化绑定时,才需要调用该方法。

答案 1 :(得分:0)

我在 GitHub 问题跟踪器上发现了类似的问题。 作为解决方法,尝试将您的方法调用更改为 lambdas 或删除它们,如本评论/github 问题的末尾所示。

我现在面临类似的事情(从今天开始 - 学习飞镖 + 颤振);我会尽快分享解决方案。干杯。

https://github.com/rekab-app/background_locator/issues/221

@Test
public void TestDist() {
    
     System.setProperty("webdriver.chrome.driver", "C:\\Users\\...\\eclipse-workspace\\...\\...\\src\\main\\java\\...\\...\\drivers\\chromedriver.exe");  
     WebDriver driver=new ChromeDriver();  
       
     // Launch Website  
     driver.navigate().to("https://www.freemaptools.com/distance-between-canada-postcodes.htm");   
     driver.manage().window().maximize();  
         
     JavascriptExecutor js = (JavascriptExecutor)driver;  
     js.executeScript("scrollBy(0, 500)");  
     
     driver.findElement(By.xpath("//*[@id=\"content\"]/form/table/tbody/tr[2]/td[1]/input")).sendKeys("N3S 7X6");
     driver.findElement(By.xpath("//*[@id=\"content\"]/form/table/tbody/tr[2]/td[3]/input")).sendKeys("N3r 7X6");
     driver.findElement(By.xpath("//*[@id=\"content\"]/form/table/tbody/tr[2]/td[4]/p")).click();
     try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     String strDist = driver.findElement(By.xpath("//*[@id=\"tb_transport\"]")).getText();
     System.out.println(strDist);
} 

看 - 有和你类似的问题。

<块引用>

这很奇怪。我解决了它分离和只传递引用 对于每个函数,我的意思是:

不好的方式

Future<bool> init() async {
  await BackgroundLocator.initialize();
  return true;
}

void startLocationService() {
  BackgroundLocator.registerLocationUpdate(callBack,
      initCallback: (as) {
        // print('===============INIT=================');
      },
      initDataCallback: {},
      disposeCallback: () {
        // print('==================DISPOSE=======================');
      },
      autoStop: false,
      androidSettings: AndroidSettings(
          accuracy: LocationAccuracy.HIGH,
          interval: 60,
          distanceFilter: 0,
          androidNotificationSettings: AndroidNotificationSettings(
              notificationChannelName: 'Location tracking',
              notificationTitle: 'Te estamos rastreandos',
              notificationMsg: 'aaaaaaaaaaaaaaaaaa',
              notificationBigMsg: 'ddddddddddddddddddddddddddddddddddddd',
              notificationIcon: '',
              notificationIconColor: Colors.grey,
              notificationTapCallback: () {
                print('===========TAP IN NOTIFICATION==================');
              })));
}

callBack(LocationDto location) {
  print('*/////////////////////${DateTime.now()}////////////////////');
}

好方法


initCallback: (params){
     //code to execute
}

initCallback: myInitCallback,

答案 2 :(得分:0)

我也遇到了这个问题。然而,@badasz 的回答并不是一个解决方案,因为 github issue 中讨论的异常是一个完全不同的异常。就我而言,我在调用 SharedPreferences.getInstance() 之前运行了代码runApp(Widget app)。这导致了给定的错误。