Home > Back-end >  How do I compare two list in expect function of flutter unit testing?
How do I compare two list in expect function of flutter unit testing?

Time:03-23

List<int> l1=[1,2,3]; List<int> l2=[1,2,3]; expect (l1,l2);

This is the code I'm using in Flutter unit testing.

Eventhough both of the list has the same content I'm not able to pass the test. I'm not able to find the usecase of comparing lists using Equatable in Flutter unit testing. Can someone please help? Thanks!

CodePudding user response:

You can use the method ListEquality().equals() to check if two List are equal.

import 'package:collection/collection.dart';

List<int> l1 = [1,2,3];  
List<int> l2 = [1,2,3];
final bool equal = ListEquality().equals(l1, l2):
expect(equal, true);

CodePudding user response:

List equality works differently in Dart. Since everything is an object you need a mechanism to check each element.

You can use either the ListEquality class to compare two lists if they do not have nested objects/informations or, if you want to compare nested objects/informations you can use DeepCollectionEquality. Both come from collections library which comes out of the box with Dart.

You can check the following examples of the usages:

import 'package:collection/collection.dart';

void main() {
  const numberListOne = [1,2,3];
  const numberListTwo = [1,2,3];
  
  final _listEquality = ListEquality();
  print(_listEquality.equals(numberListOne, numberListTwo));
}

  • Related