[Flutter]TextButton自定义样式

在Flutter中,TextButton是一个简单的文本按钮,它遵循当前的Theme。如果你想要修改TextButton的样式,可以通过设置其style属性来实现,该属性接收一个ButtonStyle对象。

给TextButton和里面Text添加背景后,效果如下。可以看到它有一个最小宽度,对于短内容的Button就感觉有一个很宽的内边距了。

自定义过后的样式如下

下面介绍如何自定义

1. 使用ButtonStyle直接定义样式

Dart 复制代码
TextButton(
  onPressed: () {
    // 按钮点击事件
  },
  style: ButtonStyle(
	backgroundColor: MaterialStateProperty.all<Color>(Colors.blue), // 设置背景颜色
	padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.zero), // 设置内边距为零
	minimumSize: MaterialStateProperty.all<Size>(Size(44, 30)),
	tapTargetSize: MaterialTapTargetSize.shrinkWrap,
	alignment: Alignment.center,
	shape: MaterialStateProperty.all<RoundedRectangleBorder>(
	RoundedRectangleBorder(
		borderRadius: BorderRadius.circular(10.0), // 设置圆角半径
	),
	),
	side: MaterialStateProperty.all<BorderSide>(
		BorderSide(width: 1.0, color: Colors.white), // 设置边框宽度和颜色
	),
	iconColor: MaterialStateProperty.all<Color?>(Colors.white),
	iconSize: MaterialStateProperty.all(15),
  ),
  child: Row(
    mainAxisSize: MainAxisSize.min,
    children: [
      Icon(Icons.add), // 图标
      SizedBox(width: 5.0), // 图标和文本之间的间距
      Text('Button'), // 文本
    ],
  ),
)

2. 使用TextButton.styleFrom静态方法

TextButton.styleFrom是一个便捷的静态方法,用于快速自定义按钮样式。

Dart 复制代码
TextButton(
	onPressed: () {
		// 按钮点击事件
	},
	style: TextButton.styleFrom(
		backgroundColor: Colors.blue,
		padding: EdgeInsets.zero,
		minimumSize: Size(60, 30),
		tapTargetSize: MaterialTapTargetSize.shrinkWrap,
		alignment: Alignment.centerLeft,
		shape: RoundedRectangleBorder(
			borderRadius: BorderRadius.circular(10.0), // 设置圆角半径
		),
		side: BorderSide(width: 1.0, color: Colors.white), // 设置边框宽度和颜色
		iconColor: Colors.white,
	),
	child: Row(
		mainAxisSize: MainAxisSize.min,
		children: [
		  	Icon(Icons.add), // 图标
		  	SizedBox(width: 5.0), // 图标和文本之间的间距
		  	Text('Button'), // 文本
		],
	),
)

3. 覆盖Theme中的默认样式

如果你想要为应用中所有的TextButton设置统一的内边距,可以通过覆盖默认的Theme来实现。

Dart 复制代码
Theme(
	data: Theme.of(context).copyWith(
		textButtonTheme: TextButtonThemeData(
			style: ButtonStyle(
			 	...
			),
			//style: TextButton.styleFrom(
			// 	...
			//),
		),
	),
	child: Row(
		mainAxisSize: MainAxisSize.min,
		children: [
		  	TextButton(
			    onPressed: () { },
			    child: Text('Button1'),
			),
			TextButton(
			    onPressed: () { },
			    child: Text('Button2'),
			),
			TextButton(
			    onPressed: () { },
			    child: Text('Button3'),
			),
		],
	),
)
相关推荐
孤鸿玉16 小时前
Fluter InteractiveViewer 与ScrollView滑动冲突问题解决
flutter
叽哥1 天前
Flutter Riverpod上手指南
android·flutter·ios
BG2 天前
Flutter 简仿Excel表格组件介绍
flutter
zhangmeng2 天前
FlutterBoost在iOS26真机运行崩溃问题
flutter·app·swift
恋猫de小郭2 天前
对于普通程序员来说 AI 是什么?AI 究竟用的是什么?
前端·flutter·ai编程
卡尔特斯2 天前
Flutter A GlobalKey was used multipletimes inside one widget'schild list.The ...
flutter
w_y_fan2 天前
Flutter 滚动组件总结
前端·flutter
醉过才知酒浓2 天前
Flutter Getx 的页面传参
flutter
火柴就是我3 天前
flutter 之真手势冲突处理
android·flutter
Speed1233 天前
`mockito` 的核心“打桩”规则
flutter·dart