当我们在开发遵循 Material Design 规范应用的时候,我们可能会需要为某个 Widgets 的点击加入涟漪效果。

Flutter 提供了 InkWell Widget 来实现这个功能。

步骤

  • 创建一个想要点击的 Widget

  • InkWell Widget 包裹它,并设置回调函数, 就可以显示涟漪动画了。

  1. // The InkWell Wraps our custom flat button Widget
  2. InkWell(
  3. // When the user taps the button, show a snackbar
  4. onTap: () {
  5. Scaffold.of(context).showSnackBar(SnackBar(
  6. content: Text('Tap'),
  7. ));
  8. },
  9. child: Container(
  10. padding: EdgeInsets.all(12.0),
  11. child: Text('Flat Button'),
  12. ),
  13. );

完整例子

  1. import 'package:flutter/material.dart';
  2. void main() => runApp(MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. final title = 'InkWell Demo';
  7. return MaterialApp(
  8. title: title,
  9. home: 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 Scaffold(
  19. appBar: AppBar(
  20. title: Text(title),
  21. ),
  22. body: Center(child: 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 InkWell(
  31. // When the user taps the button, show a snackbar
  32. onTap: () {
  33. Scaffold.of(context).showSnackBar(SnackBar(
  34. content: Text('Tap'),
  35. ));
  36. },
  37. child: Container(
  38. padding: EdgeInsets.all(12.0),
  39. child: Text('Flat Button'),
  40. ),
  41. );
  42. }
  43. }

Ripples Demo