Flutter 使用 Theme.of(context).textTheme 使常数值无效

Flutter invalide constant value using Theme.of(context).textTheme

您好,为什么在小部件中使用 Theme.of(context).themeText.headline4 时会出现“无效常量值”错误。除了我的小部件之外,它在其他任何地方都有效。

这是我的代码: 这个有效

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
          style: Theme.of(context).textTheme.headline1,
        ),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          const SizeBox(size: 20),
          buildCalculator(),
          const Text(
            'You have pushed this buttons this many times:'
,
          ),
          Text(
            '$_counter',
            style: Theme.of(context).textTheme.headline4, //No error here
          ),
        ],
      ),
      // ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

但是这个没有,它说常量值无效

  Widget buildConvertor() {
    ThemeData:
    defaultTheme;
    return Row(
      children: [
        Container(
          child: const Text(
            "Text here",
            style: Theme.of(context).textTheme.headline4, //this is where the error is
          ),
        ),
        const Spacer(
          flex: 1,
        ),
        Column(
          children: const <Widget>[Text("More text")],
        ),
      ],
    );
  }

两者都在同一个 class 下,为什么它们的行为不同。 请帮我解决问题。我只需要主题方面的帮助

由于 Theme.of(context).textTheme.headline4 的类型不是常量。

对于 Text 使用 const,style 的值必须是常量。

这里是解决方案。

Widget buildConvertor() {
    ThemeData:
    defaultTheme;
    return Row(
      children: [
        Container(
          child: Text(
            "Text here",
            style: Theme.of(context).textTheme.headline4,
          ),
        ),
        const Spacer(
          flex: 1,
        ),
        Column(
          children: const <Widget>[Text("More text")],
        ),
      ],
    );
  }

A const 是一个不会改变的常量,所以当有可以改变的参数时你不能将它声明为 const.

Text(
  "Text here",
  style: Theme.of(context).textTheme.headline4, //these are arguments so the Text cannot be const
)

但在这里,您可以将其声明为 const

const Text(
  "Text here",
  style: TextStyle(fontSize: 15), //style cannot change here so you can declare the Text as const
)

您甚至可以将样式声明为 const,因为它不会改变

const Text(
   "Text here",
   style: const TextStyle(fontSize: 15),
)