我在布局中有四个MaterialButton
,我想在按下其中一个按钮时更改所有按钮的颜色。其中两个使用一种颜色,另两个使用另一种颜色。我该怎么办?
答案 0 :(得分:1)
只需调用setState()
并使用不同的颜色即可。
这里是一个例子:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Color color1 = Colors.blue;
Color color2 = Colors.blue;
void _changeColor() {
setState(() {
color1 = Colors.red;
color2 = Colors.green;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Test"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Buttons',
),
],
),
),
floatingActionButton: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FloatingActionButton(
backgroundColor: color1,
onPressed: _changeColor,
child: Icon(Icons.refresh),
),
FloatingActionButton(
backgroundColor: color1,
onPressed: _changeColor,
child: Icon(Icons.refresh),
),
FloatingActionButton(
backgroundColor: color2,
onPressed: _changeColor,
child: Icon(Icons.refresh),
),
FloatingActionButton(
backgroundColor: color2,
onPressed: _changeColor,
child: Icon(Icons.refresh),
),
],
),
);
}
}