import 'package:flutter/material.dart';
Widget justButton({
String btText = '',
Color bgColor = Colors.blue,
Color? txtColor = Colors.white,
Color borderColor = Colors.black,
void Function() onpressedAction,//here iam getting problem
}) {
return OutlinedButton(
//i wanted to refactor this onpressed
onPressed: () {
print('Go to events Page');
},
child: Text(btText),
style: OutlinedButton.styleFrom(
backgroundColor: bgColor,
primary: txtColor,
side: BorderSide(color: borderColor)),
);
}
This is my code here I have trying to refactor the onpressed outlinedButton ,
How can it possible to refactor a function
Did you want to fix error?
Here is my refactoring result.
import 'package:flutter/material.dart';
Widget justButton({
String btText = '',
Color bgColor = Colors.blue,
Color? txtColor = Colors.white,
Color borderColor = Colors.black,
Function? onpressedAction,//here iam getting problem
}) {
return OutlinedButton(
//i wanted to refactor this onpressed
onPressed: () => onpressedAction!(),
child: Text(btText),
style: OutlinedButton.styleFrom(
backgroundColor: bgColor,
primary: txtColor,
side: BorderSide(color: borderColor)),
);
}
The onpressed method accepts a VoidCallBack type, which is just a fancy way of saying void function(). Except, it doesn't contain any space, You can see for yourself here. So declare it like this.
Widget justButton({
....
VoidCallBack? onpressedAction,
}){
return OutlinedButton(
....
onPressed: onpressedAction,
....
}
create function like this
Widget customOutlinedButton(Function? func){
return OutlinedButton(
onPressed: func,
child: Text(btText),
style: OutlinedButton.styleFrom(
backgroundColor: bgColor,
primary: txtColor,
side: BorderSide(color: borderColor)),
);
}
now just pass the function you want to call in when onpressed
customOutlinedButton(*your function here*);
Related
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
);
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;
});
},
Does anybody know how to enable/disable a Flutter ElevatedButton? I've reviewed the documentation but I can't see anything that is obvious.
class IcoButton extends StatelessWidget {
IcoButton(
{#required this.lbl,
#required this.col,
#required this.ico,
#required this.onPress});
final String lbl;
final FaIcon ico;
final MaterialColor col;
final Function onPress;
#override
Widget build(BuildContext context) {
return ElevatedButton.icon(
label: Text(lbl),
icon: ico,
style: ElevatedButton.styleFrom(
primary: col,
onPrimary: Colors.white,
minimumSize: Size(160.0, 60.0),
textStyle: TextStyle(
fontSize: 24,
),
),
onPressed: onPress,
);
}
}
Passing null to the onPressed callback will disable the button.
If onPressed and onLongPress callbacks are null, then the button will be disabled.
https://api.flutter.dev/flutter/material/ElevatedButton-class.html
I use a member variable "_isDisable" to enable button or not. Put below code in the build function to init the view:
ElevatedButton(
onPressed: _isDisable? null : callBackFunction,
child: Text("submit"),
style: ButtonStyle(),
);
when you want to disable button, call
setState(() {
_isDisable = true;
});
when you want to enable button, call
setState(() {
_isDisable = false;
});
As others have pointed out, setting the onPressed callback to null will deactivate the button for you.
Note however that it is the callback itself that must be null, not its return, so like this:
onPressed: null,
And not like this
onPressed: () => null,
onPressed: () {
if (isDisabled == true) { return; }
setState(() { int a = 10; });
}
The proper way to do it is by passing null to the onPress callback as #Shannon and #ASAD HAMEED have mentioned. However, the AbsorbPointer widget is also worth a look.
I would like to know whether there is a way to avoid the color tweening that happens upon clicking on a RawMaterialButton and FlatButton. There is a slight animation between the default color and the highlight color. I want this color switch to happen instantaneously.
Sample Button:
child: RawMaterialButton(
onPressed: () {},
highlightColor: Colors.red,
splashColor: Colors.transparent,
fillColor: Colors.blue,
elevation: 0.0,
highlightElevation: 0.0,
animationDuration: Duration.zero,
focusColor: Colors.transparent,
),
Make your own custom button using a GestureDetector. There is likely no way of getting what you want with these button types without modifying the source.
I created a sample button that instantly changes between the default and highlight color and takes an onTap parameter as well so it can be used very similarly to the button types you're used to.
class CustButton extends StatefulWidget {
CustButton({this.onTap});
final VoidCallback onTap;
#override
_CustButtonState createState() => _CustButtonState();
}
class _CustButtonState extends State<CustButton> {
Color buttonColor = Colors.blue;
#override
Widget build(BuildContext context) {
return Container(
color: buttonColor,
child: GestureDetector(
onTapDown: (details) {
setState(() {
buttonColor = Colors.red;
});
widget.onTap();
},
onTapUp: (details) {
setState(() {
buttonColor = Colors.blue;
});
},
),
);
}
}
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