Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first element of list if it exists in dart

Tags:

arrays

list

dart

I was wondering if there is a way to access the first element of a list in dart if an element exists at all, and otherwise return null.

First, I thought this would do the job:

final firstElement = myList?.first;

This works if myList is null or myList.length > 0, but would give me an error if myList is an empty List.

I guess I could do something like this:

final firstElement = (myList?.length ?? 0) > 0 ? myList.first : null;

But I was wondering if there is a simpler way of doing what I'm trying to do out there.

like image 272
dshukertjr Avatar asked Oct 18 '19 07:10

dshukertjr


2 Answers

Now you can import package:collection and use the extension method firstOrNull

import 'package:collection/collection.dart';

void main() {

  final myList = [];

  final firstElement = myList.firstOrNull;

  print(firstElement); // null
}
like image 152
Edwin Liu Avatar answered Sep 30 '22 07:09

Edwin Liu


For Dart 2.12 (with null-safety) adding an extension function might be a good idea:

extension MyIterable<T> on Iterable<T> {
  T? get firstOrNull => isEmpty ? null : first;

  T? firstWhereOrNull(bool Function(T element) test) {
    final list = where(test);
    return list.isEmpty ? null : list.first;
  }
}
like image 31
bartektartanus Avatar answered Sep 30 '22 08:09

bartektartanus