flutter_bluetooth_serial icon indicating copy to clipboard operation
flutter_bluetooth_serial copied to clipboard

The getter 'address' was called on null. Bluetooth connection to a device

Open riteshghimire9090 opened this issue 3 years ago • 1 comments

I am getting error of: The getter 'address' was called on null. Bluetooth connection to a device

import 'dart:convert'; import 'dart:typed_data';

import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

class Obd { BluetoothConnection connection; String address; String _messageBuffer = '';

void initObd(address) { BluetoothConnection.toAddress(address).then((_connection) { print('Connected to the device'); connection = _connection;

  connection.input.listen(_onDataReceived).onDone(() {
    print("Is Connected: " + _connection.isConnected.toString());
  });
}).catchError(
  (error) {
    print('Cannot connect, exception occured');
    print(error);
  },
);

}

void _onDataReceived(Uint8List data) { // Allocate buffer for parsed data

int backspacesCounter = 0;
data.forEach((byte) {
  print(byte);
  if (byte == 8 || byte == 127) {
    backspacesCounter++;
  }
});
Uint8List buffer = Uint8List(data.length - backspacesCounter);
int bufferIndex = buffer.length;

// Apply backspace control character
backspacesCounter = 0;
for (int i = data.length - 1; i >= 0; i--) {
  if (data[i] == 8 || data[i] == 127) {
    backspacesCounter++;
  } else {
    if (backspacesCounter > 0) {
      backspacesCounter--;
    } else {
      buffer[--bufferIndex] = data[i];
    }
  }
}

// Create message if there is new line character
String dataString = String.fromCharCodes(buffer);
int index = buffer.indexOf(13);
if (~index != 0) {
  _messageBuffer = dataString.substring(index);
  print("////////////////////////1");
  print(index);
  print("////////////////////////");
} else {
  _messageBuffer = (backspacesCounter > 0
      ? _messageBuffer.substring(
          0, _messageBuffer.length - backspacesCounter)
      : _messageBuffer + dataString);
  print("////////////////////////2");
  print(_messageBuffer);
  print("////////////////////////");
}

}

void sendMessage(String text) async { print(text); text = text.trim(); print(text);

if (text.length > 0) {
  try {
    connection.output.add(utf8.encode("1"));
    await connection.output.allSent;

    print("ll");
  } catch (e) {
    print(e);

    // Ignore error, but notify state

  }
  print("Send Successfully");
}

} }

riteshghimire9090 avatar May 13 '21 12:05 riteshghimire9090

The null-safe branch has just been merged. It still has a few unsafe casts to non-nullable in it, but in principle it should give you a much better idea of what could be null and what can't. If you use the current master version from Git, you could check if this flags the problematic call.

nightscape avatar Jul 04 '21 20:07 nightscape