Widget.Variable 无法从 stful 构造函数访问字符串变量

Widget.Variable Does not work to access string variable form stful constructor

我在有状态 class 中构建了一个带有一个字符串参数的构造函数,然后当我使用 widget.label 调用此参数时,它给我这个错误

“无效的常数值。”

这是我的代码:

import 'package:flutter/material.dart';

class TextFieldDecoration extends StatefulWidget {
  final String? label;
  const TextFieldDecoration({Key? key, this.label}) : super(key: key);
  @override
  _TextFieldDecorationState createState() => _TextFieldDecorationState();
}

class _TextFieldDecorationState extends State<TextFieldDecoration> {
  @override
  Widget build(BuildContext context) {
    return const TextField(
      decoration: InputDecoration(
        labelStyle: TextStyle(color: Colors.black45),
        labelText: widget.label,
      ),
      style: TextStyle(
        color:  Color(0xff1f8ac0),
      ),
    );
  }
}

发生错误是因为您将 TextField 定义为常量,但您的变量不能是常量。要解决您的问题,只需删除 TextField.

前面的 const
class _TextFieldDecorationState extends State<TextFieldDecoration> {
  @override
  Widget build(BuildContext context) {
    return TextField(
      decoration: InputDecoration(
        labelStyle: TextStyle(color: Colors.black45),
        labelText: widget.label,
      ),
      style: TextStyle(
        color:  Color(0xff1f8ac0),
      ),
    );
  }
}