0
@override
Widget build(BuildContext context) {
  const one = SizedBox();
  const two = SizedBox();

  print('${identical(one, two)}'); // prints false, should print true
  return Container();
}

Am I doing something wrong?

iDecode
  • 22,623
  • 19
  • 99
  • 186

1 Answers1

0

Nope, you're not doing something wrong. The answer comes out false simply because they are two entirely separate objects when stored in memory.

identical and similar methods used to check for equality only see if the underlying objects or reference variables are the same and not the classes they belong to.

Proof:

Widget build(BuildContext context) {
    const one = const SizedBox();
    const two = const SizedBox();
    print(one.hashCode);
    print(two.hashCode);
    print('${identical(one, two)}'); // 
    print('${one==two?'t':'f'}');
    return MaterialApp(home: Container(child: Text('_'),));

Output:

I/flutter ( 3657): 779669181 
I/flutter ( 3657): 731265968 
I/flutter ( 3657): false 
I/flutter ( 3657): f
cmd_prompter
  • 1,566
  • 10
  • 16
  • Thanks for your answer. `they are two entirely separate objects when stored in memory.` -- Can you please provide some link/reference supporting your statement? – iDecode Dec 20 '19 at 10:12
  • [Check this out](https://stackoverflow.com/questions/11704971/why-are-two-identical-objects-not-equal-to-each-other) it's in JS but the concept remains the same. I couldn't find a document pertaining to this in dart. The hash-codes for the two objects are different too hence proving that they are two totally seperate objects. – cmd_prompter Dec 20 '19 at 17:34