Search code examples
flutterandroid-studiodartbluetoothmobile-application

Null safelty Flutter causing late initialiation error


I am building a flutter app to communicate via bluetooth. When the app is connecting to the other end I get this error for few seconds on the screen until the connection is established then it goes away whish is like this:

On a red screen: LateInitializationError: Field 'connection' has not been initialized.

I think what is causing this error is this line:

late BluetoothConnection connection ;

But if I remove the late then I get an error because of the null safety. I tried to disable the null safety on the whole project but the error didnt stopp.

I also tried to make it nullable :

BluetoothConnection? connection ;

but then i get other errors in other properties depending on it : The property 'isConnected' can't be unconditionally accessed because the receiver can be 'null'.

  bool get isConnected => connection.isConnected;

Solution

  • For those who had similar issue, here is how I solved it: First I changed the declaration form to:

    BluetoothConnection? connection ;
    
      bool isConnecting = true;
    
     bool get isConnected => (connection?.isConnected ?? false);
    
      bool isDisconnecting = false;
    

    To make BluetoothConnection nullable and then I added some changes to the rest of the code to solve the errors I got. Previous code:

    connection.input?.listen
    

    New code:

    connection!.input!.listen
    

    Thanks to @jameslin