轻按功能颤振

时间:2018-07-15 12:01:08

标签: dart flutter

你好,我想为我的图标创建一个 onTap 选项,我的代码是这样的,我不知道该怎么做,你可以帮我吗。这是我的代码:

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

2 个答案:

答案 0 :(得分:8)

改为使用IconButton

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

在您的代码中,您可以这样使用

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

答案 1 :(得分:2)

创建按钮并将其包装在 GestureDetector 中,并带有 onTap 回调

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'),
      ),
    );
  }
}

重要提示: 对于用户交互性,您可以使用 onPressed 属性。