[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'),
			),
		],
	),
)
相关推荐
玲珑Felone8 小时前
从flutter源码看其渲染机制
android·flutter
ALLIN1 天前
Flutter 三种方式实现页面切换后保持原页面状态
flutter
Dabei1 天前
Flutter 国际化
flutter
Dabei1 天前
Flutter MQTT 通信文档
flutter
Dabei1 天前
Flutter 中实现 TCP 通信
flutter
孤鸿玉1 天前
ios flutter_echarts 不在当前屏幕 白屏修复
flutter
前端 贾公子1 天前
《Vuejs设计与实现》第 16 章(解析器) 上
vue.js·flutter·ios
tangweiguo030519872 天前
Flutter 数据存储的四种核心方式 · 从 SharedPreferences 到 SQLite:Flutter 数据持久化终极整理
flutter
0wioiw02 天前
Flutter基础(②④事件回调与交互处理)
flutter
肥肥呀呀呀2 天前
flutter配置Android gradle kts 8.0 的打包名称
android·flutter