Error adding key to `const Text`. Regression in flutter.gradle?


I’m getting an inconsistency on Android Studio Chipmunk (2021.2.1 Patch 1) and the Flutter compiler (3.0.5). The issue is the compiler fails with an error when I try to add a const Key to a const Text.

To repro, I created a new flutter project flutter create test and then added the key like this:

        const Text(
          key: Key('someKeyName'),    // <- I added this key
          'You have pushed the button this many times:',

The error generated is:

Launching lib/main.dart on sdk gphone64 arm64 in debug mode...
Running Gradle task 'assembleDebug'...
lib/main.dart:50:19: Error: Constant evaluation error:
        const Text(
lib/main.dart:51:20: Context: The variable '(unnamed)' is not a constant, only 
constant expressions are allowed.
          key: Key('someKeyName'),    // <- Added this key

FAILURE: Build failed with an exception.

* Where:

'/<my user path>/development/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 1156

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command '/Users/Richard.Coutts/development/flutter/bin/flutter'' 
finished with non-zero exit value 1

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at

Exception: Gradle task assembleDebug failed with exit code 1

I believe my change should work because the Key is also const. When I remove the const from const Text the compiler is happy but intellisense is not:

enter image description here

Is this a regression or am I missing something?


@pma07pg’s answer of putting the positional param first fixed the compile the error but as shown below, the second Text widget compiles fine and the positional param isn’t first? So, it seems like positional params have to go first for const declarations? (As described here positional arguments don’t have to go first anymore. This is a recent Dart change.)

const Text(
  key: Key('someKeyName'),    // <- Generates the error above
  'You have pushed the button this many times:',
  key: const Key('anotherKeyName'),    // <- This key works fine
  style: Theme.of(context).textTheme.headline4,


You need to reorder the arguments. Non-named arguments go first:

    const Text(
      'You have pushed the button this many times:',
      key: Key('someKeyName'),

Seems like the compile error isn’t correct.

Answered By – pma07pg

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

(*) Required, Your email will not be published