我是flutter的新手,我只是在学习flutter的所有基础知识。我偶然发现了按钮小部件和按下的函数,我创建了一个简单的容器,里面有一个按钮,如下所示
这是容器
Container(
child: Padding(
padding: const EdgeInsets.only(top: 25.0, left: 30),
child: Text("Item 1", style: TextStyle(
color: Colors.lightBlueAccent,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
),这是按钮
child: FloatingActionButton(
onPressed(){},
child: Text("+", style: TextStyle(
fontSize: 20,
),
),
backgroundColor: Colors.lightBlue,
),我想让按钮具有将容器背景更改为某种颜色的功能,例如蓝色。但是我想我在网上找不到答案。有没有我可以应用的方法或者我不知道存在的代码?
提前感谢!!
发布于 2020-06-07 03:32:16
虽然你已经从jitsm555得到了一个很好的答案,但这里仍然是完整的例子,我希望这对你有进一步的帮助。
import 'package:flutter/material.dart';
void main() {
runApp(ColorChange());
}
class ColorChange extends StatefulWidget {
@override
_ColorChangeState createState() => _ColorChangeState();
}
class _ColorChangeState extends State<ColorChange> {
//Initially color is set to yellow which will be changed when button is pressed
Color color = Colors.yellow;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Change Container Color"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: 300,
height: 300,
color: color, //value of color which we will change by pressing buttons
),
/* Below Row of Button when pressed will fire up
the setState and the state of our default color variable will
change according to Button which is pressed
*/
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
color: Colors.red,
child: Text("Red"),
onPressed: () {
setState(() {
color = Colors.red;
});
},
),
RaisedButton(
color: Colors.green,
child: Text("Green"),
onPressed: () {
setState(() {
color = Colors.green;
});
},
),
RaisedButton(
color: Colors.blue,
child: Text("Blue"),
onPressed: () {
setState(() {
color = Colors.blue;
});
},
),
],
),
],
),
),
),
);
}
}输出:

发布于 2020-06-07 03:15:19
声明默认材质颜色
MaterialColor _color = Colors.green;在onPressed()中更改上面的颜色
Container(
color: _color,
child: RaisedButton(onPressed: () {
setState(() {
_color = Colors.blue; // This change Container color
});
}),
)https://stackoverflow.com/questions/62236764
复制相似问题