How to create an empty list in Dart

2019-07-17 21:01发布

问题:

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?

This is a Q&A style post I made after finding the answer in the Dart usage guide. My answer is below.

回答1:

There are a few ways to create an empty list in Dart:

[]
List()
<String>[]
List<String>()

However, the Effective Dart Usage Guide recommends this:

[]

Or if you need to specify the type, then this:

<String>[]