Flutter: type ‘Null’ is not a subtype of type ‘String’ [Solved]

Today you will learn how to solve the type ‘Null’ is not a subtype of ‘String’ error in Flutter.

You see this error because you are assigning null to the String type variable.

This is a runtime error and you are assigning values dynamically when your app is running.

Example: Produce type ‘Null’ is not a subtype of type ‘String’ Error

One use case is you are parsing value from the Json to the dart objects.

And

Your dart model object variable expects string from the JSON map value.

But it receives null.

And you get your type ‘Null’ is not a subtype of ‘String’ error.

Type 1: When Creating Object

Code:

import 'package:flutter/material.dart';

import 'season 2/null_is_not_subtype_of_string.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.green),
      debugShowCheckedModeBanner: false,
      home: const CodeWithHussainPage(),
    );
  }
}


class CodeWithHussainPage extends StatelessWidget {
  const CodeWithHussainPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Code with Hussain')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            final map = {'name': null}; //This is the null that we are assigning
            User.fromMap(map);
          },
          child: const Text('Produce Error'),
        ),
      ),
    );
  }
}

class User {
  late final String name;

  User(this.name);

  User.fromMap(Map<String, dynamic> map) {
    name = map['name']; //Here we producing error on runtime
  }
}

Output:

Error is shown in the below Terminal

Type 2: Using .toString()

Text(map['name'].toString()) //Try to convert into a String

But here map['name'] is null.

And again you are getting the same error.

type ‘Null’ is not a subtype of ‘String’

Solution 1: Use Ternary Operator

You have to check that the value is not Equal to null.

name = (map['name'] != null) ? map['name'] : '';

Solution 2: Null Checking Expressing

name = map['name'] ?? '';

You can also first use the toString().

name = map['name']?.toString()??'';

Conclusion:

In this flutter error solution, you learn how you can solve type ‘Null’ is not a subtype of ‘String’ error in Flutter.

Also Read:

Thanks!

Hussain Humdani

Hussain Humdani

while ( ! ( succeed = try() ) );