gpt4 book ai didi

flutter - 如何动态改变FloatingActionButton的颜色?

转载 作者:行者123 更新时间:2023-12-03 04:01:08 24 4
gpt4 key购买 nike

如何动态改变FloatingActionButton的颜色?我想这样但这是行不通的。如何运作?

Color _background = Colors.white;
Color _foreground = Colors.green[900];
FloatingActionButton(
heroTag: null,
elevation: 10.0,
onPressed: () {
setState(() {
_background = _foreground;
});
},
child: Icon(Icons.directions_walk, color: _foreground),
backgroundColor: _background,
),

最佳答案

您的代码实际上应该没问题,我认为问题在于您的变量

Color _background = Colors.white;
Color _foreground = Colors.green[900];

在您的构建函数中。

例如:

这行不通
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
Color _background = Colors.white;
Color _foreground = Colors.green[900];
return Scaffold(
floatingActionButton: FloatingActionButton(
heroTag: null,
elevation: 10.0,
onPressed: () {
setState(() {
_background = _foreground;
});
},
child: Icon(Icons.directions_walk, color: _foreground),
backgroundColor: _background,
),
body: Text("Hello"));
}
}

这会工作
class _MyAppState extends State<MyApp> {
Color _background = Colors.white;
Color _foreground = Colors.green[900];
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
heroTag: null,
elevation: 10.0,
onPressed: () {
setState(() {
_background = _foreground;
});
},
child: Icon(Icons.directions_walk, color: _foreground),
backgroundColor: _background,
),
body: Text("Hello"));
}
}

但这不会切换您的背景颜色,此代码只能更改一次颜色。

关于flutter - 如何动态改变FloatingActionButton的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56685391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com