Reputation: 33
i'm new to flutter and i'm just learning all the basic for flutter. i came across the button widget and on pressed function and i create a simple container which have a button in it like this
here is the container
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,
),
),
),
and here is the button
child: FloatingActionButton(
onPressed(){},
child: Text("+", style: TextStyle(
fontSize: 20,
),
),
backgroundColor: Colors.lightBlue,
),
and i want to make the button have a function to change the container background to a certain color, like blue for example. but i cant seem to found the answer on the internet, i guess for me. is there any method which i can apply or code that i didn't know existed?
thanks in advance!!
Upvotes: 2
Views: 5131
Reputation: 10655
Although you already got a wonderful answer from jitsm555 still Here is full-example, I hope this helps you further.
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;
});
},
),
],
),
],
),
),
),
);
}
}
Output:
Upvotes: 3
Reputation: 34210
Declare Default Material Color
MaterialColor _color = Colors.green;
Change above color inside onPressed()
Container(
color: _color,
child: RaisedButton(onPressed: () {
setState(() {
_color = Colors.blue; // This change Container color
});
}),
)
Upvotes: 4