I'm trying to make buttons that turn grey after having been pressed. I read up on how to do this. The best way I could find is to set the material color with a ternary operator and then change the condition for that in a setState(() {}) block:
Container vehicleButton(IconData icon_, String text_, {required Function onClickAction}){
const double buttonSizeX = 200;
const double buttonSizeY = 100;
const double iconSize = 60;
const double buttonTextSize = 15;
const double buttonMargin = 5;
Color buttonColor = const Color(0xff2196f3);
const Color iconColor = Color(0xffffffff);
const Color buttonTextColor = Color(0xffffffff);
bool pressed = false;
return Container(padding: const EdgeInsets.only(left: buttonMargin, right: buttonMargin, top: buttonMargin, bottom: buttonMargin), child: SizedBox.fromSize(
size: Size(buttonSizeX, buttonSizeY), child: Material(color: pressed ? Color.fromARGB(255, 143, 143, 143) : buttonColor, child: InkWell(
onTap: () {
setState(() {
pressed = true;
});
onClickAction();
},
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
Icon(icon_, color: iconColor, size: iconSize),
Text(text_, style: TextStyle(fontSize: buttonTextSize, color: buttonTextColor)),
])))));
}
However, I'm getting a warning that the code after the ? in my ternary operator is dead code. And indeed, the button does not turn grey after pressing.
I thought maybe the values of Material are final and cannot be changed, but this wouldn't explain why all the examples I could find on the internet use this method.
You have:
Container vehicleButton(...) {
bool pressed = false;
return Container(
...
child: SizedBox.fromSize(
...
child: Material(
color: pressed ? Color.fromARGB(255, 143, 143, 143) : buttonColor,
child: InkWell(
onTap: () {
setState(() {
pressed = true;
});
onClickAction();
},
The Dart analysis tools are correctly reporting that that Color.fromARGB(...) is dead code because the conditional ternary operator checks the state of the local pressed variable, which at the time it's checked, is always false. Although the onTap handler sets pressed = true, it's setting the state of the local pressed variable, which will never be read again.
You likely intend for pressed to be a member variable of whatever State class contains the vehicleButton method.
Instead of using a SizedBox I suggest you to use the buttons provided by flutter dev: https://docs.flutter.dev/release/breaking-changes/buttons
A simple try you can give is:
RaisedButton(
child: new Text('Attention'),
textColor: Colors.white,
color: pressColor ? Colors.grey : Colors.blue, //Choose your personal colors
onPressed: () => setState(() => pressColor = !pressColor), //change the button colors
);
Related
I have a blue grey button that when pressed, turns green and then when pressed again turns back to blue grey. I now need that same button to also tick up an integer when pressed and then to tick down the integer when pressed again.
here is the code:
class _MainPageState extends State<MainPage> {
int secondaryLeftCounter = 0; //integer to change
bool so1HasBeenPressed01 = false;
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(50.0),
child: InkWell(
onTap: () {
setState(() {
so1HasBeenPressed01 = !so1HasBeenPressed01;
});
},
child: Container(
width: 30.0,
height: 30.0,
color: so1HasBeenPressed01
? Colors.green
: Colors.blueGrey[900],
),
),
),],);
I can make it work if there are two buttons (one for ticking up and one for ticking down) but am struggling to get it to work with everything happening with the same button.
cheers
Use this code:
onTap: () {
setState(() {
so1HasBeenPressed01 = !so1HasBeenPressed01;
if(so1HasBeenPressed01)
secondaryLeftCounter++;
else
secondaryLeftCounter--;
});
},
I have used a package group_button 4.2.1 but once i select the textfields the radio buttons deselect and i have to select again, i have tried using the controller property of the Widget but i didn't get it to work.
I was thinking if i can make a container from scratch that is a radio button and can retain the value once i finish filling the form to be submitted to my firestore database.
You can use List of button text and keep tract of selectedIndex.
Run on dartPad
int? _selectedValueIndex;
List<String> buttonText = ["ForSale", "For rent"];
Widget button({required String text, required int index}) {
return InkWell(
splashColor: Colors.cyanAccent,
onTap: () {
setState(() {
_selectedValueIndex = index;
});
},
child: Container(
padding: const EdgeInsets.all(12),
color: index == _selectedValueIndex ? Colors.blue : Colors.white,
child: Text(
text,
style: TextStyle(
color: index == _selectedValueIndex ? Colors.white : Colors.black,
),
),
),
);
}
Inside build method to use this,
Row(
children: [
...List.generate(
buttonText.length,
(index) => button(
index: index,
text: buttonText[index],
),
)
],
),
Hi I am still new to flutter but was trying to make a pretty simple app I thought.
This app consists of 30 buttons each in their own container. Code to follow. All I am trying to do is if a button is pressed then it will turn orange and then if it is longPressed that it goes back to its default color of white. Can someone explain how to do this. Here is an example of just 1 button.
Container(
width: 65,
height: 65,
child: MaterialButton(
shape: CircleBorder(
side: BorderSide(
width: 5,
color: Colors.blue[900],
style: BorderStyle.solid)),
child: Text(
"1",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
color: Colors.white,
textColor: Colors.black,
onPressed: () {
setState(() {
color:
Colors.orange;
});
},
onLongPress: (){
setState(() {
color:
Colors.white;
});
},
),
),
Thanks in Advance
//declare color variable
Color myColor=Colors.white;
//set myColor to material button
color:myColor;
//in setstate use it like this
setState({
myColor=Colors.white; or myColor=Colors.orange;
})
first define a Color
Color buttonColor = Colors.white;
then pass this color to your button
MaterialButton(color: buttonColor)
after this inside your onPressed function
onPressed: () {
setState(() {
buttonColor =
Colors.orange;
});
},
I'm trying to create a simple vertical scrolling calendar.
Problem is that I can't manage to find a way to reset back to previous state in case I tap on a new container.
Here's the code:
class CalendarBox extends StatelessWidget {
BoxProprieties boxProprieties = BoxProprieties();
Map item;
CalendarBox({this.item});
bool selected = false;
#override
Widget build(BuildContext context) {
return Consumer<Producer>(
builder: (context, producer, child) => GestureDetector(
onTap: () {
print(item['dateTime']);
selected = producer.selectedState(selected);
},
child: AnimatedContainer(
duration: Duration(milliseconds: 100),
color: selected == true ? Colors.blue : Colors.grey[200],
height: 80,
width: 50,
margin: EdgeInsets.only(top: 5),
child: Column(
children: [
Text(
'${item['dayNum']}',
style: TextStyle(
fontWeight: FontWeight.bold,
color: boxProprieties.dayColor(item['dateTime'])),
),
],
),
),
),
);
}
}
Here's the situation:
One way to achieve it is, create a model for boxes and keep a value current selected block, in your model you will have the index assigned to that block,
int currentSelected =1; //initial value
class Block{
int id;
..
.. // any other stuff
}
now in your code, the check modifies to
block.id == currentSelected ? Colors.blue : Colors.grey[200],
your on tap modifies to
onTap: () {
setState(){
currentSelected = block.id
};
},
If you want to prevent the rebuild of the whole thing every time you can use valueNotifire for current selected block. Hope this gives you an idea.
I have a TextField that serves as a search bar where the user can use the built in Android/iOS keyboard to type but also has the possibility to insert a special characters in the search bar from a button. In a way the typing and the other insertion is combined into one string
use case: The user types hell in the search bar then presses the button widget the search bar value becomes : hellö
I set up everything but when I click the button nothing happens (the typing from the keyboard works fine)
Here's my code:
//I have this as a global variable
TextEditingController _searchInputControllor = TextEditingController();
//This is the TextField
class _SearchBarState extends State<SearchBar> {
#override
Widget build(BuildContext context) {
return TextField(
enableInteractiveSelection: false,
controller: _searchInputControllor,
cursorColor: primaryDark,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 15.0),
border: InputBorder.none,
hintText: "Search...",
suffixIcon: Material(
color: Colors.white,
elevation: 6.0,
borderRadius: BorderRadius.all(Radius.circular(6.0),),
child: InkWell(
splashColor: Colors.greenAccent,
onTap: () {},
child: Icon(Icons.search, color: primaryDark,),
),
),
),
);
}
}
//This is the button widget
//It is supposed to add to the search bar but nothing happens
class _SpecialCharState extends State<SpecialChar> {
#override
Widget build(BuildContext context) {
return ButtonTheme(
minWidth: 40.0,
child: FlatButton(
color: Colors.transparent,
textColor: Colors.black,
padding: EdgeInsets.all(8.0),
splashColor: Colors.blue,
onPressed: () {
setState(() {
_searchInputControllor.text = _searchInputControllor.text + widget.btnVal.toLowerCase();
});
},
child: Text(
widget.btnVal
),
)
);
}
}
A. No problem at all
I think your code is working well as I tried on my Android Phone Demo.
The text field is changed as I tap the buttons.
B. Change cursor position
Nonetheless, I add this code to make the cursor automatically placed on last character.
Rather than directly changed the text, we copy its value which contains selection.
Later we offset its selection by length of newText
void appendCharacters() {
String oldText = _searchInputControllor.text;
String newText = oldText + widget.btnVal.toLowerCase();
var newValue = _searchInputControllor.value.copyWith(
text: newText,
selection: TextSelection.collapsed(
offset: newText.length, //offset to Last Character
),
composing: TextRange.empty,
);
_searchInputControllor.value = newValue;
}
so we can trigger the method with code below :
Widget build(BuildContext context) {
return ButtonTheme(
minWidth: 40.0,
child: FlatButton(
onPressed: appendCharacters, // call a function
),
);
}
Working App Repository
You may look into this repo and build yourself. Github