Skip to content

Instantly share code, notes, and snippets.

@Alexi-Zemcov
Created August 8, 2023 12:19
Show Gist options
  • Save Alexi-Zemcov/4ebe0a3d5fb9225b4e5f173d39498db6 to your computer and use it in GitHub Desktop.
Save Alexi-Zemcov/4ebe0a3d5fb9225b4e5f173d39498db6 to your computer and use it in GitHub Desktop.
Что делать если нужно список с nullable значениями присвоить переменной к списку с not nullable?
void main() async {
// Что делать если нужно список с nullable значениями присвоить переменной к списку с not nullable?
// Исходные данные - список с nullable значениями.
final nullableList = [null, 1, 2, null, 3, 4]; // RuntymeType is List<int?>
// 1) Удалили все null:
nullableList.removeWhere((e) => e == null); // но тип всё еще List<int?>.
// 2) Как не надо делать:
// final List<int> justList = nullableList; // Ошибка анализатора - List<int?> can't be assigned to List<int>.
// final List<int> justList = nullableList as List<int>; // Ошибка рантайма List<int?> is not a subtype of type List<int>.
// 3) Как надо делать:
final List<int> justList = List<int>.from(nullableList); // Всё супер, так рааботает!)
print(justList.runtimeType);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment