Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty list in Dart

Tags:

list

flutter

dart

I want to create an empty list for a Flutter project.

final prefs = await SharedPreferences.getInstance(); final myStringList = prefs.getStringList('my_string_list_key') ?? <empty list>; 

I seem to remember there are multiple ways but one recommended way. How do I do it?

like image 857
Suragch Avatar asked Jan 04 '19 00:01

Suragch


People also ask

How do you make an empty list in darts?

To create an empty list, use [] for a growable list or List. empty for a fixed length list (or where growability is determined at run-time). The created list is fixed-length if length is provided. The list has length 0 and is growable if length is omitted.

How do you create a list in Dart?

Using addAll() method to add all the elements of another list to the existing list. Creating a new list by adding two or more lists using addAll() method of the list. Creating a new list by adding two or more list using expand() method of the list. Using + operator to combine list.

How do you handle empty list in Flutter?

How to check List is empty or not in Dart Flutter using isEmpty property in dart. isEmpty always return boolean value true or false . - true : return if the list is empty. - false : return if the list is non-empty.


1 Answers

There are a few ways to create an empty list in Dart. If you want a growable list then use an empty list literal like this:

[] 

Or this if you need to specify the type:

<String>[] 

Or this if you want a non-growable (fixed-length) list:

List.empty() 

Notes

  • In the past you could use List() but this is now deprecated. The reason is that List() did not initialize any members, and that isn't compatible with null safe code. Read Understanding null safety: No unnamed List constructor for more.
  • Effective Dart Usage Guide
like image 164
Suragch Avatar answered Oct 07 '22 06:10

Suragch