在设计应遵循Material Design指南的应用程序时,我们希望在点击时将水波动画添加到Widgets。

Flutter提供了InkWellWidget来实现这个效果。

步骤

  1. 创建一个可点击的Widget。
  2. 将它包裹在一个InkWell中来管理点击回调和水波动画。
  1. // The InkWell Wraps our custom flat button Widget
  2. new InkWell(
  3. // When the user taps the button, show a snackbar
  4. onTap: () {
  5. Scaffold.of(context).showSnackBar(new SnackBar(
  6. content: new Text('Tap'),
  7. ));
  8. },
  9. child: new Container(
  10. padding: new EdgeInsets.all(12.0),
  11. child: new Text('Flat Button'),
  12. ),
  13. );

完整的例子

  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 = 'InkWell 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. // The InkWell Wraps our custom flat button Widget
  30. return new InkWell(
  31. // When the user taps the button, show a snackbar
  32. onTap: () {
  33. Scaffold.of(context).showSnackBar(new SnackBar(
  34. content: new Text('Tap'),
  35. ));
  36. },
  37. child: new Container(
  38. padding: new EdgeInsets.all(12.0),
  39. child: new Text('Flat Button'),
  40. ),
  41. );
  42. }
  43. }