Flutter组件基础——TextButton

TextButton可简单理解为按钮,即可点击的Text
常用属性如下:

  • TextButton常用属性:
    • autofocus
    • child
    • clipBehavior
    • enabled
    • focusNode
    • onLongPress
    • onPressed
    • style

来看一下,定义三个按钮,分别对应,按钮不可点击,按钮可点击,按钮带有渐变背景,三种情况,效果如下:

Flutter组件基础——TextButton - 图1

使用代码如下:

  1. class MyApp extends StatelessWidget {
  2. const MyApp({Key? key}) : super(key: key);
  3. static const String _title = 'Flutter Code Sample';
  4. @override
  5. Widget build(BuildContext context) {
  6. return MaterialApp(
  7. title: _title,
  8. home: Scaffold(
  9. appBar: AppBar(
  10. title: const Text(_title),
  11. ),
  12. body: const MyStatelessWidget(),
  13. ));
  14. }
  15. }
  16. class MyStatelessWidget extends StatelessWidget {
  17. const MyStatelessWidget({Key? key}) : super(key: key);
  18. @override
  19. Widget build(BuildContext context) {
  20. return Center(
  21. child: Column(
  22. mainAxisSize: MainAxisSize.min,
  23. children: [
  24. TextButton(
  25. onPressed: null,
  26. child: const Text('Disabled'),
  27. style: TextButton.styleFrom(
  28. textStyle: const TextStyle(fontSize: 20),
  29. ),
  30. ),
  31. const SizedBox(
  32. height: 30,
  33. ),
  34. TextButton(
  35. onPressed: () {},
  36. child: const Text('Enabled'),
  37. style: TextButton.styleFrom(
  38. textStyle: const TextStyle(fontSize: 20),
  39. ),
  40. ),
  41. const SizedBox(
  42. height: 30,
  43. ),
  44. ClipRRect(
  45. borderRadius: BorderRadius.circular(4),
  46. child: Stack(
  47. children: [
  48. Positioned.fill(
  49. child: Container(
  50. decoration: const BoxDecoration(
  51. gradient: LinearGradient(
  52. colors: [
  53. Color(0xFF0D47A1),
  54. Color(0xFF1976D2),
  55. Color(0xFF42A5F5),
  56. ],
  57. ),
  58. ),
  59. ),
  60. ),
  61. TextButton(
  62. onPressed: () {},
  63. child: const Text('Gradient'),
  64. style: TextButton.styleFrom(
  65. padding: const EdgeInsets.all(16.0),
  66. primary: Colors.white,
  67. textStyle: const TextStyle(fontSize: 20),
  68. ),
  69. ),
  70. ],
  71. ),
  72. )
  73. ],
  74. ),
  75. );
  76. }
  77. }

注意渐变按钮的实现,使用了Stack

参考

Text Button Api Doc