OwO OwO
OwO OwO

Reputation: 51

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.

Upvotes: 4

Views: 410

Answers (1)

Nisanth Reddy
Nisanth Reddy

Reputation: 6430

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.

Upvotes: 6

Related Questions