Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are const Widgets in Dart not identical?

When we call identical() on two widgets created using their const constructors, it return false. Whereas while calling the same for two non widget objects it returns true.

Why is that ?

void main() {

  final a = const Center(
    child: const Padding(padding: const EdgeInsets.all(8),)
  );

  final b = const Center(
    child: const Padding(padding: const EdgeInsets.all(8),)
  );

  assert(identical(a, b)); // false


  var a1 = const EdgeInsets.all(8);

  var b1 = const EdgeInsets.all(8);


  assert(identical(a1, b1)); // true

}

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 'package:todo_improve/main.dart': Failed assertion: line 17 pos 8: 'identical(a, b)': is not true.

like image 832
OwO OwO Avatar asked Sep 18 '25 03:09

OwO OwO


1 Answers

After much research, this is what I found out.

Now one main difference between your first and second cases is that a and b are Widgets in first case while in second case they are not.

Now, flutter has a --track-widget-creation flag which is enabled by default in debug modes.

This is the main culprit which makes your seemingly const widgets as non identical.

Now this means that when you run your app in release mode, your widgets will indeed be compile time constants and thus the identical function would indeed return true.

Change your code to (changing because assert calls are ignored in release mode)

final a =  const Center(
  child: const Padding(padding: const EdgeInsets.all(8),)
);

final b = const Center(
  child: const Padding(padding: const EdgeInsets.all(8),)
);

print(identical(a, b));

Then try running your code in release mode using flutter run --release and check your console to see that true will be printed. If you run in debug using flutter run, you will see false in the console.

Refer to this thread for more info.

like image 97
Nisanth Reddy Avatar answered Sep 20 '25 18:09

Nisanth Reddy