Trouble with calling function using onPressed in Flutter

Issue

I am trying to call a function upon an onPressed in Flutter.

I’ve tried

onPressed: (){ 
   _showDialog;
},

and

onPressed: _showDialog,

and

onPressed: () => _showDialog,

This is my function.

  void _showDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("Title"),
          content: Text("Body"),
          actions: <Widget>[
            FlatButton(
              child: Text("Close"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

I keep getting “invalid constant value”.

EDIT:

This is where I’m calling onPressed:

                      secondary: const IconButton(
                        icon: Icon(Icons.domain),
                        onPressed: (){
                          _showDialog();
                        },
                      ),

Error when onPressed

Solution

UPDATE

Easy fix: remove const keyword

      secondary: IconButton(
                    icon: Icon(Icons.domain),
                    onPressed: (){
                      _showDialog();
                    },
                  ),

Old Answer

You should try like these ways:

onPressed: (){ 
   _showDialog();
},

or

onPressed: _showDialog,

or

onPressed: () => _showDialog(),

Answered By – diegoveloper

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *