Ad

How To Fix Error: Non-nullable Variable To Be Used?

- 1 answer

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

Answer

  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;
}
Ad
source: stackoverflow.com
Ad