為了讓使用者更容易點擊,實務上會讓整列都能被點擊,必須使用 GestureDector
、Container
、Row
三層 widget 所包裝。
Version
Flutter 3.24.5
Flutter
- Android 與 iOS 都成功使用
GestureDetector
實現讓整列都能被點擊
GestureDetector
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() => _Home();
}
class _Home extends State<Home> {
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text("GestureDetector Row"),
);
var clickableRow = GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text(
'Hello World',
),
),
);
},
child: Container(
color: Colors.transparent,
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
SizedBox.shrink(),
Text("Clickable Row"),
Icon(Icons.arrow_forward_ios),
],
),
),
);
var body = Center(
child: clickableRow,
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 17
var clickableRow = GestureDetector(
child: Container(
child: Row(
),
),
)
clickableRow
:若要實現整列都能被點擊,則必須被GestureDector
、Container
、Row
三層 widget 所包裝
Line 30
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
SizedBox.shrink(),
Text("Clickable Row"),
Icon(Icons.arrow_forward_ios),
],
),
Row
: 將同一列多個 widget 整合成單一 widget
Line 27
Container(
color: Colors.transparent,
padding: const EdgeInsets.all(16.0),
),
Container
:讓整列都能接受 tapcolor: Colors.transparent
:GestureDetector
必須Container
有顏色才會有效,可實際設定背景色,就算沒有顏色也要補上Colors.transparent
Line 17
GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text(
'Hello World',
),
),
);
}
)
GestureDector
:偵測 taponTap()
:處理 tap 事件
Conclusion
- GestureDetector 只有對有底色的 Container 有反應,如果設計沒有底色,也要加上
color: Colors.transparent