Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading