Text 部件 不能直接设置点击事件
1. 如果单独给 一个文字设置 点击事件, 可以使用TextSpan 部件
- 点击 word 文字添加事件
class MyHomePage extends StatelessWidget {
var i = 1;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
Container(
child: Text.rich(
TextSpan(
children: [
TextSpan(
text: "hello",
style: TextStyle(fontSize: 29, color: Colors.red),
),
TextSpan(
text: "world",
style: TextStyle(fontSize: 59, color: Colors.yellow),
// 设置点击事件
recognizer: TapGestureRecognizer()
..onTap = () {
debugPrint("${i++}");
},
),
],
),
),
),
],
),
);
}
}
2. 使用 InkWell 给文字添加水波纹高亮效果 点击 事件
注意:如果给 Container 添加上了 背景色, 将会看不到高亮效果, 一些配置高亮颜色的参数,将会看不到效果
class MyHomePage extends StatelessWidget {
var i = 1;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
Center(
child: InkWell(
child: Container(
padding:
EdgeInsets.only(left: 10, right: 10, bottom: 10, top: 5),
child: Text("自定义点击"),
decoration: BoxDecoration(
border: Border.all(width: 1, color: Colors.blue),
borderRadius: BorderRadius.circular(5),
),
),
highlightColor: Colors.blue,
splashColor: Colors.red,
onTap: () {
print('${i++}');
},
),
)
],
),
);
}
- 比如如下这样的, 点击后, 水波纹效果将不再有效果
3. 设置带背景色 的高亮水波纹 效果(Material 和 InkWeel 组合使用)
class MyHomePage extends StatelessWidget {
var i = 1;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
Center(
child: Container(
margin: EdgeInsets.all(20),
child: Material(
color: Colors.red,
child: InkWell(
child: Container(
padding: EdgeInsets.only(
left: 10,
right: 10,
bottom: 10,
top: 5,
),
child: Text("自定义点击"),
),
onTap: () {
print('${i++}');
},
),
),
decoration: BoxDecoration(
border: Border.all(width: 1, color: Colors.blue),
borderRadius: BorderRadius.circular(5),
),
),
)
],
),
);
}
}