Why can't I use a UniqueKey for a widget?

0

Issue

I don’t understand how we are supposed to assign a UniqueKey to an object if the compiler doesn’t let us.

This code fails if I use the second option:

body: const Center
(
    child: Note(key: ValueKey('note'), initialValue: 'test'), // WORKS
    child: Note(key: UniqueKey(), initialValue: 'test'), // ERROR
),
class Note extends StatefulWidget
{
    final String initialValue;

    const Note({required Key key, this.initialValue = ""}) : super(key: key);

gives this error:

Error: Cannot invoke a non-'const' constructor where a const expression is
expected.
Try using a constructor or factory that is 'const'.

How can I change this to allow UniqueKey to work please?

Solution

You need to remove const form your code as const requires a constant while while UniqueKey() changes itself.

body: Center
(
    child: Note(key: ValueKey('note'), initialValue: 'test'), // WORKS
    child: Note(key: UniqueKey(), initialValue: 'test'), // ERROR
),

Answered By – Diwyansh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More