我是扑扑的新手,我只是学习扑扑的所有基本知识。我遇到了按钮小部件并按下了功能,然后创建了一个简单的容器,里面有一个这样的按钮
这是容器
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,
),
并且我想使按钮具有将容器背景更改为某种颜色(例如蓝色)的功能。但是我想我似乎无法在互联网上找到答案。有什么我可以应用的方法或我不知道存在的代码?
提前谢谢!
答案 0 :(得分:3)
声明默认材料颜色
fetch
在onPressed()内更改上述颜色
push
答案 1 :(得分:1)
尽管您仍然从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;
});
},
),
],
),
],
),
),
),
);
}
}
输出: