How can I implement OnPressed callback for Text widget, Flutter

66,133

Solution 1

Just wrap your title in a GestureDetector to handle clicks. Then call Navigator's pushNamed to redirect to a new route.

new GestureDetector(
  onTap: () {
    Navigator.pushNamed(context, "myRoute");
  },
  child: new Text("my Title"),
);

Solution 2

Use InkWell

this gives you nice ripple effect as well

 new InkWell(
          onTap: () {
            Navigator.pushNamed(context, "YourRoute");
          },
          child: new Padding(
            padding: new EdgeInsets.all(10.0),
            child: new Text("Tap Here"),
          ),
        );

or

new FlatButton(
          onPressed: () {
            Navigator.pushNamed(context, "YourRoute");
          },
          child: new Text("Tap Here"),
        )

Solution 3

For All the widget of Flutter you can implement onPressed using these widget

1. InkWell() : Using this widget you can add ripple effect on clicking

InkWell(
     onTap: () {
         Navigator.pushNamed(context, "write your route");
     },
     child: new Text("Click Here"),
 );


2. GestureDetector() : Using this widget you can implement, onTap, onDoubleTap, onLongPress and many more

GestureDetector(
     onTap: () {
         Navigator.pushNamed(context, "write your route");
     },
     onLongPress: (){
        // open dialog OR navigate OR do what you want
     }
     child: new Text("Save"),
 );

Solution 4

You can use TextButton. Since it has a transparent background, it will look like a text widget.

            TextButton(
              onPressed: () {
                //action
              },
              child: Text(
                'Title Text', //title
                textAlign: TextAlign.end, //aligment
              ),
            ),
Share:
66,133
Fathima km
Author by

Fathima km

Updated on March 12, 2021

Comments

  • Fathima km
    Fathima km about 3 years

    I have a Text widget on pressing which another Route has to be shown. But I could not see any onPressed() method for the Text widget. Please Help.

  • Meshugah
    Meshugah almost 4 years
    I got started with Flutter last week. It's literally the most amazing developer experience I've ever come accross. Wonderful.
  • iDecode
    iDecode almost 4 years
    So you are combining both the answers and writing your own? I like that
  • Sanjayrajsinh
    Sanjayrajsinh about 3 years
    No, I improve the above answers and write my own @iDecode
  • D B
    D B almost 3 years
    Point for explanations.
  • passerby
    passerby about 2 years
    FlatButton has been deprecated. Use TextButton instead.