Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get button press to work in flutter

Tags:

flutter

dart

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")],
            ),
          ),
        ],
      ))
    ]);
  }
}
like image 788
Xathene Avatar asked May 16 '18 00:05

Xathene


People also ask

Why button is not working in Flutter?

Because, if onPressed() property is not provided, even with the empty function, RaisedButton is considered as disabled.

How do I get back on button click in Flutter?

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.


1 Answers

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:

Pass a tear-off

 new RaisedButton(
   onPressed: _buttonWasPressed, // no `()`,
   child: ...
 )

Pass a closure

 new RaisedButton(
   onPressed: () {
     // do something.
   },
   ..
 )
like image 148
Jonah Williams Avatar answered Nov 01 '22 09:11

Jonah Williams