2

I am new to flutter and Dart language. Can someone please explain to my why geek1==geek2 is false when it should be true by principle. function gfg() returns same value everytime then why geek1 and geek2 are not equal?

gfg() => [1, 2];     
// Main function
void main() {
  // Assiging value
  // through function
  var geek1 = gfg();
  var geek2 = gfg();
   
  // Printing result
  // false
  print(geek1 == geek2);
  print(geek1);
  print(geek2);
}
Rehan
  • 131
  • 1
  • 8

2 Answers2

1

Object equality is evaluated by reference in Dart - Basically, you are creating two different objects, which are stored at two different memory addresses. When the Dart runtime compares the objects, it compares their memory addresses, rather than their content by default.

To compare two List objects in terms of their contents, you can use the listEquals function.

Some extra info:

To compare classes for equality, you can override the equality operator, or you can use the Equatable package.

Michael Horn
  • 3,819
  • 9
  • 22
  • when I add const in function returning object type like this gfg() =>const [1, 2]; then geek1==geek2 is true. why is it then? What does const do – Rehan Aug 18 '21 at 21:53
  • 1
    With the const modifier, the value is compiled directly into your application, as part of the machine code instructions. Non-const values are computed at runtime and stored on the stack. The reason the equality works with the const modifier is because the function will always return a pointer to the address of the compiled value. – Michael Horn Aug 18 '21 at 22:02
0

Because gfg is a function which returns a new array on every call.

You're comparing them with ==, which is the operator for doing identity comparison, not value comparison (a.k.a. equality). Since the instances are always distinct, they're never identical.

Alexander
  • 59,041
  • 12
  • 98
  • 151