Dart| Flutter How to: Create an Empty List

This tutorial shows multiple ways to create an empty list in Dart or Flutter List

An empty list is a list without an element and the size of a list is zero.

Sometimes, In Flutter, API or service method returns an empty list instead of null to have better handling of null safety.

How to create an Empty List in Flutter or dart?

An empty list can be created in multiple.

usually, In Dart, you can create an object using type and brackets ().

  var list = List(); // throws an error during compilation because of null safety

The above code, throws Error: Can’t use the default List constructor..

Dart does not allow to use of default constructors without initializing data, It causes null safety errors.

Let’s multiple ways to create an empty or blank list in dart.

The first way, assign the empty data with the [] syntax.

    var list = [];
    print(list.runtimeType); //JSArray<dynamic>

This creates an empty array list without elements.

Second way, using the List.empty() method

  var list = List.empty();
  print(list.runtimeType); //JSArray<dynamic>

All the above are generic typed with dynamic values.

The third way, If you want to create a typed empty number list, You have to assign with generic with int.

var numbers = <int>[];
print(numbers.runtimeType); //JSArray<int>

For another example, let’s create an empty list string.

  var words = <String>[];
  print(words.runtimeType);//JSArray<String>

The fourth way is, Create an Empty Object List.

create a class of employees and create a List empty object using var emps = <Employee>[];

Here is an example code

class Employee {
  final int id;
  final String name;
  final int salary;
  final DateTime joinDate;

  Employee(this.id, this.name, this.salary, this.joinDate);

}

void main() {
  var emps = <Employee>[];
  print(emps.runtimeType);
}

Finally, This is not an Empty List, but create a fixed list with initialized zero values.

List created with fixed elements with default zero values.

  var numbers = List<int>.filled(10, 0);
  print(numbers); //[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Conclusion

This tutorial talks about multiple ways to create an empty list with int, string, and objects.