serjo macken
serjo macken

Reputation: 445

Add on tap function flutter

hello guys i want to create an onTap option for my icon, my code is like this and I cant figure out how to do so can you help me.this is my code:

trailing: new Column(
                    children: <Widget>[
                      new Container(
                        child: new Icon(Icons.bookmark),
                        margin: EdgeInsets.only(top: 25.0),
                      )
                    ],
                  ),

Upvotes: 20

Views: 44076

Answers (2)

Robin
Robin

Reputation: 5427

Create the button and Wrap it in a GestureDetector with an onTap callback

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'Gesture Demo';

    return MaterialApp(
      title: title,
      home: MyHomePage(title: title),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(child: MyButton()),
    );
  }
}

class MyButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Our GestureDetector wraps our button
    return GestureDetector(
      // When the child is tapped, show a snackbar
      onTap: () {
        final snackBar = SnackBar(content: Text("Tap"));

        Scaffold.of(context).showSnackBar(snackBar);
      },
      // Our Custom Button!
      child: Container(
        padding: EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: Theme.of(context).buttonColor,
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Text('My Button'),
      ),
    );
  }
}

Important : for user interactivity, you can use onPressed property.

Upvotes: 13

Dhaval
Dhaval

Reputation: 2874

Use IconButton instead.

new IconButton(
  icon: new Icon(Icons.bookmark),
  onPressed: () { /* Your code */ },
)

In your code, you can use like this

trailing: new Column(
                    children: <Widget>[
                      new Container(
                        child: new IconButton(
                                 icon: new Icon(Icons.bookmark),
                                 onPressed: () { /* Your code */ },
                               ),
                        margin: EdgeInsets.only(top: 25.0),
                      )
                    ],
                  ),

Upvotes: 55

Related Questions