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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With