Home > Software engineering >  Error adding key to `const Text`. Regression in flutter.gradle?
Error adding key to `const Text`. Regression in flutter.gradle?

Time:07-21

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:
Script 

'/<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 https://help.gradle.org

BUILD FAILED in 5s
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?

EDIT

@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:',
),
Text(
  key: const Key('anotherKeyName'),    // <- This key works fine
  '$_counter',
  style: Theme.of(context).textTheme.headline4,
),

CodePudding user response:

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.

  • Related