为什么我无法在 flutter 中访问自己的类中的变量

问题描述 投票:0回答:1

首先,如果我的术语有点错误,我很抱歉,但我对 flutter 还很陌生。 因此,我无法从类 _LightState extends State 部分中访问在类顶部定义的颜色变量originalColor,我无法弄清楚为什么。 testColGray 和 testCol2 是我可以访问的另一个类的静态变量。

class Light extends StatefulWidget {
  Light({required this.newColor, required this.size});
  Color newColor;
  final int size;
  Color originalColor =
      PickerAndSelector.testColGray; 

  @override
  State<Light> createState() => _LightState();
}

class _LightState extends State<Light> {
  String indicator = 'non';
  bool selected = false;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(6),
      child: GestureDetector(
        onTap: () {
          setState(() {
            if (indicator == 'non') {
              indicator = 'SEL';
              selected = true;
            } else {
              indicator = 'non';
              selected = false;
            }

            print(selected);
          });
          if (selected) originalColor = _PickerAndSelectorState.testCol2;
          // can't access originalColor here
        },
        child: Container(
          height: widget.size.toDouble(),
          width: widget.size.toDouble(),
          color: selected ? widget.newColor : widget.originalColor,
          child: Text(indicator),
        ),
      ),
    );
  }
}

我尝试在 Widget build(BuildContext context) 部分中定义originalColor,但无法从容器内访问originalColor,事实上现在不使用originalColor。

Widget build(BuildContext context) {
    Color originalColor = PickerAndSelector.testColGray;

    return Padding(
      padding: EdgeInsets.all(6),
      child: GestureDetector(
        onTap: () {
          setState(() {
            if (indicator == 'non') {
              indicator = 'SEL';
              selected = true;
            } else {
              indicator = 'non';
              selected = false;
            }

            print(selected);
          });
          if (selected) originalColor = _PickerAndSelectorState.testCol2;
          // can't access originalColor here
        },
        child: Container(
          height: widget.size.toDouble(),
          width: widget.size.toDouble(),
          color: selected ? widget.newColor : widget.originalColor,
          child: Text(indicator),
        ),
      ),
    );
  }
flutter dart variables
1个回答
0
投票

由于您正在扩展

State<Light>
,因此您可以使用
widget.originalColor

访问光的属性
if (selected) widget.originalColor = _PickerAndSelectorState.testCol2;
© www.soinside.com 2019 - 2024. All rights reserved.