如何动态更改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,
),
答案 0 :(得分:0)
您的代码实际上应该没问题,我认为问题在于您的变量
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"));
}
}
但是它不会切换背景颜色,此代码只能更改一次颜色。