简体   繁体   English

如何修复错误:要使用的不可为空的变量?

[英]How to fix Error: Non-nullable variable to be used?

In Android Studio I am getting these 2 errors when compiling:在 Android Studio 中,编译时出现以下 2 个错误:

lib/connectivity_provider.dart:60:12: Error: Non-nullable variable 'isConnected' must be assigned before it can be used.
    return isConnected;
           ^^^^^^^^^^^
lib/connectivity_provider.dart:12:8: Error: Field '_isOnline' should be initialized because its type 'bool' doesn't allow null.
  bool _isOnline;
       ^^^^^^^^^

What could I have done wrong here with return isConnected; return isConnected; ? ?

import 'dart:async';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';


class ConnectivityProvider with ChangeNotifier {
  Connectivity _connectivity = new Connectivity();

  bool _isOnline;
  bool get isOnline => _isOnline;

  startMonitoring() async {
    await initConnectivity();
    _connectivity.onConnectivityChanged.listen((
        ConnectivityResult result,
        ) async {
      if (result == ConnectivityResult.none) {
        _isOnline = false;
        notifyListeners();
      } else {
        await _updateConnectionStatus().then((bool isConnected) {
          _isOnline = isConnected;
          notifyListeners();
        });
      }
    });
  }

  Future<void> initConnectivity() async {
    try {
      var status = await _connectivity.checkConnectivity();

      if (status == ConnectivityResult.none) {
        _isOnline = false;
        notifyListeners();
      } else {
        _isOnline = true;
        notifyListeners();
      }
    } on PlatformException catch (e) {
      print("PlatformException: " + e.toString());
    }
  }

  Future<bool> _updateConnectionStatus() async {
    bool isConnected;
    try {
      final List<InternetAddress> result =
      await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isConnected = true;
      }
    } on SocketException catch (_) {
      isConnected = false;
      //return false;
    }
    return isConnected;
  }
}
  1. You need to assign default value as it is not nullable or late init variable.您需要分配默认值,因为它不可为空或后期初始化变量。

     bool _isOnline = false; //Here bool get isOnline => _isOnline;
  2. Since you are returning a future you should have a default value.由于您要返回未来,因此您应该有一个默认值。 For example in your case if it comes to non if case in try block without out throwing an execption.例如,在您的情况下,如果在 try 块中遇到非 if 情况而不抛出执行。 It will try to return non assigned value.它将尝试返回未分配的值。 So it will throw error.所以它会抛出错误。

 Future<bool> _updateConnectionStatus() async { bool isConnected = false; //Here try { final List < InternetAddress > result = await InternetAddress. lookup ('google.com'); if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) { isConnected = true; } } on SocketException catch (_) { isConnected = false; //return false; } return isConnected; }

You function return a Future, so if you return isConnected at the end you return a bool.你 function 返回一个 Future,所以如果你返回 isConnected 最后你返回一个布尔值。 You should return a Future.你应该返回一个 Future。

Try like this像这样试试

Future<bool> _updateConnectionStatus() async {
    final completer = Completer();    
    bool isConnected;
    try {
      final List<InternetAddress> result =
      await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isConnected = true;
        completer.complete(isConnected);
      }
    } on SocketException catch (_) {
      isConnected = false;
      completer.complete(isConnected);
      //return false;
    }
    return completer.future;
}

With code, you return the Future with completer.Future .使用代码,您可以使用completer.Future返回 Future。 Then when data arrived you complete the Future with completer.complete(isConnected)然后当数据到达时,您使用completer.complete(isConnected)完成 Future

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 不可为空的变量 - The non-nullable variable 错误:不可为 null 的局部变量“newTaskTitle”必须先赋值才能使用 - error: The non-nullable local variable 'newTaskTitle' must be assigned before it can be used 错误:不可为 null 的变量“mockBuildContext”必须先赋值才能使用 - Error: Non-nullable variable 'mockBuildContext' must be assigned before it can be used 不可为 null 的局部变量“title”必须先赋值,然后才能使用。 Flutter 错误 - The non-nullable local variable 'title' must be assigned before it can be used. Flutter error 错误:不可为 null 的变量“newTaskTitle”必须先赋值才能使用 - Error: Non-nullable variable 'newTaskTitle' must be assigned before it can be used 不可为 null 的变量“newTextTitle”必须先赋值才能使用 - Non-nullable variable 'newTextTitle' must be assigned before it can be used 如何解决“必须初始化不可为空的变量'_db'。尝试添加初始化表达式” - How to fix "The non-nullable variable '_db' must be initialized. Try adding an initializer expression" 不可为空的变量未初始化 - non-nullable variable is not initialized 如何修复此语法错误? 必须初始化不可为空的实例字段“学生” - How can I fix this syntax error? Non-nullable instance field 'students' must be initialized 如何修复:必须初始化不可为 null 的实例字段“userFuture”? - How to Fix : Non-nullable instance field 'userFuture' must be initialized?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM