我们不仅希望向用户展示信息,还希望我们的用户与我们的应用互动!那么,我们如何响应用户基本操作,如点击和拖动? 在Flutter中我们可以使用GestureDetector Widget!

假设我们想要创建一个自定义按钮,当点击时显示一个SnackBar。我们如何解决这个问题?

步骤

  1. 创建一个button。
  2. 把它包装在 GestureDetector中并提供一个onTap回调。
  1. // Our GestureDetector wraps our button
  2. new GestureDetector(
  3. // When the child is tapped, show a snackbar
  4. onTap: () {
  5. final snackBar = new SnackBar(content: new Text("Tap"));
  6. Scaffold.of(context).showSnackBar(snackBar);
  7. },
  8. // Our Custom Button!
  9. child: new Container(
  10. padding: new EdgeInsets.all(12.0),
  11. decoration: new BoxDecoration(
  12. color: Theme.of(context).buttonColor,
  13. borderRadius: new BorderRadius.circular(8.0),
  14. ),
  15. child: new Text('My Button'),
  16. ),
  17. );

注意

  1. 如果您想将Material 水波效果添加到按钮中,请参阅”添加Material 触摸水波“ 。
  2. 虽然我们已经创建了一个自定义按钮来演示这些概念,但Flutter也提供了一些其它开箱即用的按钮:RaisedButtonFlatButtonCupertinoButton

完整的例子

  1. import 'package:flutter/material.dart';
  2. void main() => runApp(new MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. final title = 'Gesture Demo';
  7. return new MaterialApp(
  8. title: title,
  9. home: new MyHomePage(title: title),
  10. );
  11. }
  12. }
  13. class MyHomePage extends StatelessWidget {
  14. final String title;
  15. MyHomePage({Key key, this.title}) : super(key: key);
  16. @override
  17. Widget build(BuildContext context) {
  18. return new Scaffold(
  19. appBar: new AppBar(
  20. title: new Text(title),
  21. ),
  22. body: new Center(child: new MyButton()),
  23. );
  24. }
  25. }
  26. class MyButton extends StatelessWidget {
  27. @override
  28. Widget build(BuildContext context) {
  29. // Our GestureDetector wraps our button
  30. return new GestureDetector(
  31. // When the child is tapped, show a snackbar
  32. onTap: () {
  33. final snackBar = new SnackBar(content: new Text("Tap"));
  34. Scaffold.of(context).showSnackBar(snackBar);
  35. },
  36. // Our Custom Button!
  37. child: new Container(
  38. padding: new EdgeInsets.all(12.0),
  39. decoration: new BoxDecoration(
  40. color: Theme.of(context).buttonColor,
  41. borderRadius: new BorderRadius.circular(8.0),
  42. ),
  43. child: new Text('My Button'),
  44. ),
  45. );
  46. }
  47. }