Skip to content

Invalid constant value error when extracting a widget with a const TextStyle parameter #59778

@stephane-archer

Description

@stephane-archer

Originally reported: Dart-Code/Dart-Code#5374

import 'package:flutter/material.dart';

class A extends StatelessWidget {
  const A({super.key});

  @override
  Widget build(BuildContext context) {
    const TextStyle h1 = TextStyle(color: Colors.red);
    return const Text("hello world", style: h1);
  }
}

extract widget Text("hello world", style: h1);

result:

import 'package:flutter/material.dart';

class A extends StatelessWidget {
  const A({super.key});

  @override
  Widget build(BuildContext context) {
    const TextStyle h1 = TextStyle(color: Colors.red);
    return ExtractedWidget(h1: h1);
  }
}

class ExtractedWidget extends StatelessWidget {
  const ExtractedWidget({
    super.key,
    required this.h1,
  });

  final TextStyle h1;

  @override
  Widget build(BuildContext context) {
    return const Text("hello world", style: h1);
  }
}

There is an error regarding h1 Invalid constant value.

expected result

Here is the correct code (the const keyword is not at the right place):

import 'package:flutter/material.dart';

class A extends StatelessWidget {
  const A({super.key});

  @override
  Widget build(BuildContext context) {
    const TextStyle h1 = TextStyle(color: Colors.red);
    return const ExtractedWidget(h1: h1);
  }
}

class ExtractedWidget extends StatelessWidget {
  const ExtractedWidget({
    super.key,
    required this.h1,
  });

  final TextStyle h1;

  @override
  Widget build(BuildContext context) {
    return Text("hello world", style: h1);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2A bug or feature request we're likely to work onarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-refactoringIssues with analysis server refactoringstype-bugIncorrect behavior (everything from a crash to more subtle misbehavior)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions