How to give onPressed a method in custom button flutter - dart

i have custom button and i want to add method in my onpressed from my parameter,unfortunately i'm still stuck what type should i use in my custom button parameter, curently i hard code the onpressed method and pass a string route to navigate the problem is not all my button is made to navigate there is one button to logout, i already used void in my parameter but it's still doesn't work.
here is my custom button
FlatButton buttonMenu(String title, IconData icon, String route) {
return new FlatButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(25.0)),
color: Colors.blueGrey,
child: new Container(
height: 50.0,
width: 120.0,
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Padding(
padding: EdgeInsets.only(right: 10.0),
child: new Icon(
icon,
color: Colors.white70,
size: 30.0,
),
),
new Text(
title,
style: new TextStyle(fontSize: 20.0, fontWeight: FontWeight.w300),
),
],
),
),
onPressed: () {
Navigator.of(context).pushNamed('/$route');
},
);
}
}
and here is how i call the custom button
buttonMenu('MVP Arc', Icons.star, 'EmployeeScreen')
and what i want is i can send method in my parameter to my onpressed so it will be like this
buttonMenu('MVP Arc', Icons.star, myMethod())
my method for navigate
void _navigate(String route){
Navigator.of(context).pushNamed('/$route');
}

the onPressed type is VoidCallback so make your parameter like this this type.
FlatButton buttonMenu(String title, IconData icon, VoidCallback onCustomButtonPressed )
and when you call it pass a reference to it
buttonMenu('MVP Arc', Icons.star, myMethod)
and don't forget to do the same in your function body
onPressed: onCustomButtonPressed ,
UPDATE:
if you want to pass parameters you have to declare your own Signature :
Example in your case :
typedef VoidNavigate = void Function(String route);
and then use this new type
FlatButton buttonMenu(String title, IconData icon, VoidNavigate onCustomButtonPressed)
call it like this
onPressed: (){onCustomButtonPressed},
and you pass your function like this
buttonMenu('MVP Arc', Icons.star, _navigate('EmployeeScreen'))
or you can just do it like this as #Kirill Shashov said
buttonMenu('MVP Arc', Icons.star, () {_navigate('EmployeeScreen');})

The accepted answer for passing parameters no longer seems to work on newer versions of Flutter.
In case someone searches for a similar issue, the modifications below worked for me.
Modifying Raouf Rahiche's answer, the working method as of 2019. October 28 is as follows.
Update: added mising flutter version number below
Flutter version: 1.9.1+hotfix.5
Dart version: 2.5.0
Using the existing typedef:
typedef VoidNavigate = void Function(String route);
Using the type changed in a small way, you have to pass the parameter to the button separately.
FlatButton buttonMenu(
String title,
IconData icon,
VoidNavigate onCustomButtonPressed,
String route //New addition
) {
...
}
Calling it now:
onPressed: () { onCustomButtonPressed(route); },
Passing the function:
buttonMenu('MVP Arc', Icons.star, _navigate, 'EmployeeScreen')

Here is what worked for me:
Flutter Version : 2.6.0
Dart Version : 2.15.0
in my customButton function:
Widget customButton(VoidCallback onPressed)
{
....
onPressed : onPressed.call(),
}
and no other changes needed.

the only we need to do is add .call() to the end of the function to be void.
onPressed: ()=>onPressed to onPressed: ()=>onPressed.call()

Related

How to display text in 'Text' widget after flatButton press?

I'm trying to make a calculator app using flutter where instead of taking input through the keyboard I want to take input through some buttons. The issue comes when I press a button but it does not display the corresponding data in the Text widget above.
All my classes are stateless except for the first MyApp class, which is Stateful.
I tried by creating a general variable outside all the classes and using that to transfer text from the button class to the display class but that did not work.
The general variable is "_calcText"
class DisplayAnswer extends StatelessWidget {
final String _text;
DisplayAnswer(this._text);
#override
Widget build(BuildContext context) {
return Expanded(
flex: 2,
child: Material(
color: Colors.greenAccent,
child: Ink(
padding: EdgeInsets.all(10.0),
child: Center(
child: Container(
constraints: BoxConstraints.expand(),
decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 5.0), color: Colors.white),
child: Text(_text,style: TextStyle(fontSize: 50.0), textAlign: TextAlign.center,),
),
),
),
),
);
}
}
class NumButtons extends StatelessWidget {
final String _number;
NumButtons(this._number);
#override
Widget build(BuildContext context) {
return FlatButton(
onPressed: () {
_calcText = _calcText + _number;
print(_calcText);
DisplayAnswer(_calcText);
} ,
child: Text(_number.toString(), style: TextStyle(fontSize: 30.0),),
color: Colors.white
);
}
}
I want to display the value of _calcText in the Text widget of DisplayAnswer. I want _calcText to also change as other buttons are clicked, ie; if 2 is clicked Text should only display 2, if 5 is clicked after that it should display 25
The full code is here:
https://drive.google.com/open?id=1C4MLAkjowloicbjBP_uV8BfpPzhz4Yxf
Use Statefull widget insted of StatelessWidget.
Call the setState() method on onPressed function, after adition operation. It will build your widget with a new value.
On DisplayAnswer, you have to make a function to increment the value, than pass this function as parameter to NumButtons.
Pass a callback Function to NumButtons, like:
class NumButtons extends StatelessWidget {
final String _number;
final Function callback;
...

Draggable FloatingActionButton in Flutter

I want to make a draggable floating button and if possible to print the drag position in the console.
Due to the ability to compose Flutter widgets in whatever way you want to, you can simply do it like this:
Draggable(
feedback: FloatingActionButton(child: Icon(Icons.drag_handle), onPressed: () {}),
child: FloatingActionButton(child: Icon(Icons.drag_handle), onPressed: () {}),
childWhenDragging: Container(),
onDragEnd: (details) => print(details.offset))
This Draggable can be passed as the floatingActionButton argument to a Scaffold.
The feedback parameter controls how the widget that is dragged about in the end will look like and child specifies how the stationary Draggable should look like. As you probably only want to see one FloatingActionButton at a time, you can pass an empty Container to childWhenDragging.
The Offset (position) of the drag will be printed to the console when releasing the drag.
I needed to add a positioned widget to set the position of my button
class _MyHomePageState extends State<MyHomePage> {
Offset position =Offset(20.0, 20.0);
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Stack(
children: <Widget>[
Container(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage("data_repo/img/bg1.jpg"),
fit: BoxFit.cover,
),
),
),
Positioned(
left : position.dx,
top : position.dy ,
child : Draggable(
feedback: Container(
child : FloatingActionButton(child: Icon(Icons.add), onPressed: () {})
),
child: Container(
child : FloatingActionButton(child: Icon(Icons.add), onPressed: () {}),
),
childWhenDragging: Container(),
onDragEnd: (details){
setState(() {
position = details.offset;
});
print(position);
print(position.dx);
print(position.dy);
}))
],
));
}
}
You can use the DraggableFloatingButton package: https://pub.dartlang.org/packages/draggable_floating_button

Unable to change RaisedButton color

RaisedButton(
onPressed: null,
child: Text('Get in'), // change it to sign-in
color: Colors.blue,
)
I am creating this widget under children, but the color is not getting changed from its default grey color. I tried with hex code value but still no help.
From RaisedButton documentation:
If the [onPressed] callback is null, then the button will be disabled and by default will resemble a flat button in the [disabledColor]. If you are
trying to change the button's [color] and it is not having any effect, check that you are passing a non-null [onPressed] handler.
RaisedButton color depends on is it onPress able or not like this one. You should add onPressed into the attribute
RaisedButton(
onPressed: () => {},
color: Colors.green,
child: Text(
'Login',
style: TextStyle(color: Colors.white),
),
),
Use this instead,
RaisedButton(
onPressed: null,
child: Text('Get in'), // change it to sign-in
color: Colors.blue,
disabledColor: Colors.blue,//add this to your code
)
I had this problem before, the solution is removing the null keyword from onPressed method to some implementation , at least this : () {}

flutter: button onpress action function continuously calling

When I add onPress function to the button, loadMore function is called when the app starts. And It continuously increate the page number. I couldn't find what is wrong.
Widget header(){
return new Container(
color: Colors.blue[900],
height: 40.0,
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new IconButton(
icon: new Icon(
Icons.arrow_back,
),
onPressed: loadMore(page: page = page + 1)
),
],
),
);
}
You have a function invocation, but you should pass a function reference
onPressed: () => loadMore(page: page = page + 1)
If loadMore didn't have parameters (actually when it has the same parameters the caller uses to invoke the method), you could use
onPressed: loadMore
to pass the function reference without creating an closure.
With your code
onPressed: loadMore(page: page = page + 1)
loadMore(...) will be called every time Flutter runs build()

Second page in flutter naviagtion flow is not full size

I am trying to make a basic "new activity" in flutter
I have followed the flutters docs and made a button that navigates to the next page with:
Navigator.push(context, new MaterialPageRoute(builder: (context)=> new HomePage(title: title,)));
This is the build method of the 2nd page/activity (HomePage.dart)
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Home"),
textTheme: orbitTextTheme),
body: new Center(
child: new Container(
color: Color.orange,
height: 150.0,
width: 150.0,
child:new Column(
children: <Widget>[
new TextField(
controller: _textController,
decoration: new InputDecoration(
hintText: "Try to type?"
),
)
],
),
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _newReg,
tooltip: 'New reg', //externalize
backgroundColor: Color.orange,
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
BUT, the second page is not full size: (Notice the missing floating action button)
Can anyone tell me what am doing wrong?
UPDATE
Was calling the Navigator.push( in a callback from googleSignIn (which presents a modal). So putting in a small delay fixed the bug. Thanks!
This graphical bug happens whenever you pop the last visible route before pushing a new one.
Consider using pushReplacement or pushReplacementNamed instead.

Resources