Search code examples
flutterdarterror-handlingnon-nullable

Error: Null safety features are disabled for this library in Flutter


I added non-nullabe in pubspec as well. I don't want to change my SDK version, cuz I have already been using it for other dependencies and it will cause errors if I change the version. Please let me know how can I remove this error. Please let me know how can i resolve this issue as i am new to Flutter

Error:

lib/BluetoothScanningDevices.dart:113:40: Error: Null safety features are disabled for this library.
Try removing the package language version or setting the language version to 2.12 or higher.
                children: snapshot.data!
                                       ^

My pubspec.yaml file looks like this:

name: epicare
description: Epilepsy monitoring application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"
analyzer:
  enable-experiment:
    - non-nullable
dependencies:
  table_calendar: ^2.2.1
  shared_preferences: ^0.5.4+5
  permission_handler: ^5.0.0
  contacts_service: ^0.3.10
  url_launcher: ^5.4.2
  flutter_switch: ^0.2.2
  flutter:
    sdk: flutter
  custom_switch: ^0.0.1
  charts_flutter: ^0.10.0
  image_picker: ^0.6.7+22
  loading_animations: ^2.1.0
  flutter_spinkit: ^4.1.2
  cupertino_icons: ^0.1.3
  flutter_launcher_icons: ^0.9.0
  flutter_local_notifications: ^1.4.4+2
  focused_menu: ^1.0.0
  fluttertoast: ^4.0.0
  contact_picker: ^0.0.2
  google_sign_in: ^3.3.0
  http: ^0.12.0+4
  provider: ^5.0.0
  firebase_core: ^0.5.0
  firebase_auth: ^0.18.0+1
  flutter_blue: ^0.8.0
  bluetooth_enable: ^0.1.1
  flutter_bluetooth_serial: ^0.2.2

dev_dependencies:
  flutter_test:
    sdk: flutter

Code for using Bluetooth functionality:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'BluetoothConnectBand.dart';
import 'BluetoothConnectedSuccess.dart';
import 'package:flutter_blue/flutter_blue.dart';

class BluetoothScanningDevices extends StatefulWidget {
  @override
  _BluetoothScanningDevicesState createState() =>
      _BluetoothScanningDevicesState();
}

class _BluetoothScanningDevicesState extends State<BluetoothScanningDevices> {
  FlutterBlue flutterBlue = FlutterBlue.instance;

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xffE5E0A1),
        elevation: 0,
        centerTitle: true,
        title: Text(
          "Connect Band",
          style: TextStyle(
            fontSize: 15.0,
            color: Colors.black,
            fontFamily: 'Montserrat',
            fontWeight: FontWeight.normal,
          ),
        ),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black,
          ),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) {
                  return BluetoothConnectBand();
                },
              ),
            );
          },
        ),
        actions: [
          Padding(
            padding: EdgeInsets.only(right: 5.0),
            child: FlatButton(
              onPressed: () {},
              child: Text(
                "Search",
                style: TextStyle(
                  fontSize: 15.0,
                  color: Colors.black,
                  fontWeight: FontWeight.normal,
                  fontFamily: 'Montserrat',
                ),
              ),
            ),
          )
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
              height: size.height * 0.4,
              width: size.width,
              color: const Color(0xffE5E0A1),
              child: Image.asset(
                'assets/images/bluetooth.png',
              )),
          Container(
            width: size.width,
            padding: EdgeInsets.symmetric(vertical: 20),
            child: Text(
              "Scanning Available Devices...",
              style: TextStyle(
                fontSize: 15.0,
                color: Colors.black,
                fontWeight: FontWeight.w400,
                fontFamily: 'Montserrat',
              ),
              textAlign: TextAlign.center,
            ),
          ),
          StreamBuilder<List<BluetoothDevice>>(
              stream: Stream.periodic(Duration(seconds: 2))
                  .asyncMap((_) => FlutterBlue.instance.connectedDevices),
              initialData: [],
              builder:  (c, snapshot) => Column(
                children: snapshot.data!
                    .map((d) => ListTile(
                  title: Text(d.name),
                  subtitle: Text(d.id.toString()),
                  trailing: StreamBuilder<BluetoothDeviceState>(
                    stream: d.state,
                    initialData: BluetoothDeviceState.disconnected,
                    builder: (c, snapshot) {
                      if (snapshot.data ==
                          BluetoothDeviceState.connected) {
                        return RaisedButton(
                          child: Text('OPEN'),
                          onPressed: (){}
                        );
                      }
                      return Text(snapshot.data.toString());
                    },
                  ),
                ))
                    .toList(),
              ),
          ),
      
        ],
      ),
    );
  }
}

Solution

  • In the null safety world we use "!" to indicate that the variable won't be nullable, but in order to use these cool features the dart SDK version should be greater than 2.12.

    the error message clearly states the line number where the problem exists, you need not change the version nor migrate, remove the "!" after snapshot.data on line 113 inside your BluetoothScanningDevices.dart file.

    I have added a comment inside the code snippet where the change has to happen.

     builder:  (c, snapshot) => Column(
    // Important: remove the exclamation after snapshot.data to fix the error.
                    children: snapshot.data!
                        .map((d) => ListTile(
                      title: Text(d.name),
                      subtitle: Text(d.id.toString()),
                      trailing: StreamBuilder<BluetoothDeviceState>(
                        stream: d.state,
                        initialData: BluetoothDeviceState.disconnected,
                        builder: (c, snapshot) {
                          if (snapshot.data ==
                              BluetoothDeviceState.connected) {
                            return RaisedButton(
                              child: Text('OPEN'),
                              onPressed: (){}
                            );
                          }
                          return Text(snapshot.data.toString());
                        },
                      ),
                    ))