1
    void main(){
    int a=3;
    int b=3;
    print(identical(a,b));

returns true

    double c=3.2;
    double d=3.2;
    print(identical(c,d));

returns true, same for String type

    List l1=[1,2,3];
    List l2=[1,2,3];
    print(identical(l1,l2));
    }

But for list returns false.How?.As int,double,string override ==operator does that have anything to do with identical returning true for these types.

Be happy
  • 121
  • 1
  • 6
  • probably related: https://stackoverflow.com/questions/18428735/how-do-i-compare-two-objects-to-see-if-they-are-the-same-instance-in-dart – ישו אוהב אותך Dec 12 '21 at 05:00
  • Still didn't get bro, so here my objects that I am comparing are same instances? – Be happy Dec 12 '21 at 05:16
  • 1
    `bool`, `int`, `double`, and `String` are all *immutable*, so Dart can canonicalize their literals as an optimization without affecting behavior (other than `identical` itself). The same cannot be said for `List`, `Map`, or `Set` literals since they are mutable. Two separate `[1, 2, 3]` literals cannot be canonicalized since mutating one should not affect the other. – jamesdlin Dec 12 '21 at 06:05
  • Okay thank you for answering – Be happy Dec 12 '21 at 06:12
  • 1
    @jamesdlin well described – Jahidul Islam Dec 12 '21 at 06:18

1 Answers1

2

You got the false because a list is an indexable collection of objects with a length. In identical checks, two instances are the same or not but you can convert this instance into a string.

  List l1 = [1, 2, 3, 4];
  List l2 = [1, 2, 3, 4];
  print(identical(l1.toString(), l2.toString())); //true

For list comparison, you can use listEquals

import 'package:flutter/foundation.dart';
void main() {
  List<int> l1 = [1, 2, 3,4];
  List<int> l2 = [1, 2, 3, 4];
  print(listEquals(l1, l2)); //true
}
Jahidul Islam
  • 11,435
  • 3
  • 17
  • 38