首先,如果我的术语有点错误,我很抱歉,但我对 flutter 还很陌生。
因此,我无法从类 _LightState extends State
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),
),
),
);
}
由于您正在扩展
State<Light>
,因此您可以使用 widget.originalColor
访问光的属性
if (selected) widget.originalColor = _PickerAndSelectorState.testCol2;