0
0
Fluttermobile~5 mins

Null safety in Flutter

Choose your learning style9 modes available
Introduction

Null safety helps prevent errors by making sure variables always have a value or are clearly marked as nullable.

When you want to avoid app crashes caused by missing values.
When you want to write safer and more reliable code.
When you want the compiler to help catch mistakes before running the app.
When you want to clearly show which variables can be empty and which cannot.
Syntax
Flutter
String name = 'Alice'; // non-nullable
String? nickname = null; // nullable

Use ? after the type to allow a variable to be null.

Without ?, the variable must always have a value.

Examples
This shows a non-nullable integer and a nullable integer.
Flutter
int age = 30; // cannot be null
int? maybeAge = null; // can be null
You can assign null to a nullable variable anytime.
Flutter
String? message;
message = 'Hello';
message = null;
This will cause a compile error because greeting is non-nullable.
Flutter
String greeting = 'Hi';
greeting = null; // Error: non-nullable variable cannot be null
Sample App

This app shows two texts: one from a non-nullable variable and one from a nullable variable with a default fallback.

Flutter
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    String? nullableText = null;
    String nonNullableText = 'Hello Flutter!';

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Null Safety Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(nonNullableText),
              Text(nullableText ?? 'Default Text'),
            ],
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Use the ?? operator to provide a default value when a nullable variable is null.

Null safety helps catch bugs early, making your app more stable.

Summary

Null safety means variables either always have a value or are marked to allow null.

Use ? to make a variable nullable.

Use ?? to give a default value if a nullable variable is null.