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

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

我也在 pubspec 中添加了 non-nullabe。我不想更改我的 SDK 版本,因为我已经将它用于其他依赖项,如果我更改版本会导致错误。请让我知道如何删除此错误。请告诉我如何解决这个问题,因为我是 Flutter 的新手

错误:

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!
                                       ^

我的 pubspec.yaml 文件如下所示:

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

使用蓝牙功能的代码:

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(),
              ),
          ),
      
        ],
      ),
    );
  }
}

种方法可以在遗留代码中使用不可为 null 的包,但它们需要使用 --no-sound-null-safety 调用各种命令。更好的做法是按照 https://dart.dev/null-safety/migration-guide.

中所示的步骤迁移您的代码

在空安全世界中,我们使用“!”表明变量不能为空,但为了使用这些很酷的特性,dart SDK 版本应该大于 2.12。

报错信息清楚的写明了问题所在的行号,不用改版本也不用迁移,去掉“!”在 BluetoothScanningDevices.dart 文件中的第 113 行 snapshot.data 之后。

我在必须进行更改的代码片段中添加了注释。

 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());
                    },
                  ),
                ))

如何使用不同版本的同一个包 像这样使用->(环境上面的分析器)

version: 1.0.6+13

analyzer:
  enable-experiment:
    - non-nullable

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  flutter_bloc: ^6.1.1
  bloc_provider: ^0.7.0+3
  provider: ^4.3.2+3

  shared_preferences: ^0.5.12+4
  package_info: ^2.0.0
  
  #firebase 
  firebase_core: ^1.1.0
  firebase_analytics: ^8.0.2
  firebase: ^9.0.1
  firebase_crashlytics: ^2.0.2


dependency_overrides:
  firebase_core_platform_interface: ^4.0.0
  plugin_platform_interface: ^2.0.0
  http: ^0.13.0
  http_parser: ^4.0.0
  shared_preferences: ^2.0.5
  path_provider_windows: ^2.0.0
  path_provider_platform_interface: ^2.0.0
  path_provider_linux: ^2.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter