问题
I tried to use null safety, but it's giving me this error:
This requires the 'non-nullable' language feature to be enabled. Try updating your pubspec.yaml to set the minimum SDK constraint to 2.10.0 or higher, and running 'pub get'.
I changed my Dart SDK constraint from 2.7.0
to 2.10.0
, but it's still showing this error.
Also I upgraded my Dart and Flutter SDK:
dart-sdk v2.10.2 is the latest version available based on your source(s).
Flutter (Channel stable, 1.22.3, ...
回答1:
Null safety is no longer an experiment as of Dart 2.12
. It is now easy to enable.
Enabling null safety
Starting with the first Dart 2.12
versions, types will be non-nullable by default. So you just need to change your SDK constraint:
environment:
sdk: ">=2.12.0-0 <3.0.0"
This is still a beta feature, which means that you will currently need to be on the Flutter beta
channel or later.
Learn more about "Enabling null safety" on dart.dev.
回答2:
Following the Dart documentation I was able to enable null safety in Flutter with these steps:
First add analysis_options.yaml
:
analyzer:
enable-experiment:
- non-nullable
Then move to the dev channel and upgrade:
flutter channel dev
flutter upgrade
Change the sdk in pubspec.yaml
environment:
sdk: ">=2.11.0-213.0.dev <2.12.0"
Clean the project:
flutter clean
flutter pub get
Restart the IDE (VS Code in my case).
And then it was working fine.
回答3:
I had done all the above and yet for some reason the analyzer still gave an error about enabling null safety. What fixed it for me was running pub upgrade instead of pub get. I'm not even going to try to find out why, I'm just going to get back to work!
回答4:
This can happen when you upgrade the Flutter version you're using.
Try adding the following to the analysis_options.yml
analyzer:
- enable-experiment:
- non-nullable
Then, try cleaning and upgrading the project dependencies again.
To do that, you can use the following commands:
flutter clean
flutter packages pub upgrade
flutter pub run build_runner build
Finally, restart your IDE.
P.s. By the way, make sure that the sdk you're using is compatible with your Flutter version
来源:https://stackoverflow.com/questions/64621051/how-to-enable-null-safety-in-flutter