Home > Software design >  How to fix Error: Non-nullable variable to be used?
How to fix Error: Non-nullable variable to be used?

Time:08-12

In Android Studio I am getting these 2 errors when compiling:

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;?

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;
  }
}

CodePudding user response:

  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. 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;
}

CodePudding user response:

You function return a Future, so if you return isConnected at the end you return a bool. You should return a 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. Then when data arrived you complete the Future with completer.complete(isConnected)

  • Related