Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Non-nullable By Default in Flutter?

Tags:

flutter

dart

I want to use the NNBD Dart feature in my Flutter app today, but I could not find out how to use it.

If I try to use int? et al., I get the following error:

This requires the 'non-nullable' experiment to be enabled.
like image 391
creativecreatorormaybenot Avatar asked May 13 '20 19:05

creativecreatorormaybenot


People also ask

What does non-nullable by default mean in Dart?

The Dart language now supports sound null safety! When you opt into null safety, types in your code are non-nullable by default, meaning that variables can't contain null unless you say they can.

What is non-nullable in Flutter?

This means that variables are considered non-nullable by default. If you don't give an object null support when you create it, it will never get a null . As a result, you avoid null reference errors in your code.


Video Answer


2 Answers

With Flutter 2

As of Flutter 2 (and Dart 2.12), null safety is the new default. This means that by specifying the following SDK constraint:

environment:
  sdk: '>=2.12.0 <3.0.0'

You automatically opt into null safety.

Pre Flutter 2

You need to make sure that your Dart SDK version constraint is 2.9.0 in your pubspec.yaml file (use flutter channel master):

environment:
  sdk: ">=2.9.0-8.0 <3.0.0"

Now, you can add an analysis_options.yaml file next to your pubspec.yaml file:

analyzer:
  enable-experiment:
    - non-nullable

You should not expect compilation to succeed as of now.

like image 115
creativecreatorormaybenot Avatar answered Oct 01 '22 03:10

creativecreatorormaybenot


change sdk version on given below

 environment:
      sdk: ">=2.12.0 <3.0.0"

then, run flutter pub get

like image 20
Ranjith Bobby Avatar answered Oct 01 '22 01:10

Ranjith Bobby