Ok I'm pretty new to flutter/ dart so go easy on me. I'm just trying to make a very simple app where when you press a button some text updates telling you how many times you have pressed the button. I have no idea why this code doesn't work. The button appears but nothing happens when you press it.
import 'package:flutter/material.dart';
class Homepage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[],
);
}
}
class Buttonz extends StatefulWidget {
@override
_ButtonBeingPressed createState() => new _ButtonBeingPressed();
}
class _ButtonBeingPressed extends State<Buttonz> {
int _timesPressed = 0;
_buttonWasPressed() {
setState(() {
_timesPressed++;
});
}
@override
Widget build(BuildContext context) {
return new Column(children: <Widget>[
new Center(
child: new Row(
children: <Widget>[
new Text(
'The button was pressed ' + _timesPressed.toString() + "
times"),
new RaisedButton(
onPressed: _buttonWasPressed(),
child: new Row(
children: <Widget>[new Text("Press meh")],
),
),
],
))
]);
}
}
Because, if onPressed() property is not provided, even with the empty function, RaisedButton is considered as disabled.
By tapping the Android back-button (or the "pop" button) each square turns blue, one by one. Only when all squares are blue, tapping the back-button once more will return to the previous screen.
Your problem is that you didn't pass a callback to RaisedButton
, you invoked your callback.
new RaisedButton(
onPressed: _buttonWasPressed(), // invokes function
child: new Row(children: <Widget>[new Text("Press meh")]),
);
To pass a callback to another widget you have two choices:
new RaisedButton(
onPressed: _buttonWasPressed, // no `()`,
child: ...
)
new RaisedButton(
onPressed: () {
// do something.
},
..
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With