處理點選
如何處理點選和拖動。
你不僅想向用戶顯示資訊,還希望使用者與你的應用進行互動。使用 GestureDetector 元件來響應基本操作,例如點選和拖動。
本教程展示瞭如何建立一個自定義按鈕,點選時顯示一個 snackbar,步驟如下:
- 建立按鈕。
- 用
GestureDetector包裝它,並提供一個onTap()回撥函式。
dart
// The GestureDetector wraps the button.
GestureDetector(
// When the child is tapped, show a snackbar.
onTap: () {
const snackBar = SnackBar(content: Text('Tap'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
// The custom button
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.lightBlue,
borderRadius: BorderRadius.circular(8),
),
child: const Text('My Button'),
),
)
注意事項
#- 有關如何為你的按鈕新增 Material 漣漪效果的資訊,請參閱 新增 Material 點選漣漪 教程。
- 雖然此示例建立了一個自定義按鈕,但 Flutter 包含一些按鈕實現,例如:
ElevatedButton、TextButton和CupertinoButton。
互動示例
#import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Gesture Demo';
return const MaterialApp(
title: title,
home: MyHomePage(title: title),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({super.key, required this.title});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: const Center(child: MyButton()),
);
}
}
class MyButton extends StatelessWidget {
const MyButton({super.key});
@override
Widget build(BuildContext context) {
// The GestureDetector wraps the button.
return GestureDetector(
// When the child is tapped, show a snackbar.
onTap: () {
const snackBar = SnackBar(content: Text('Tap'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
// The custom button
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.lightBlue,
borderRadius: BorderRadius.circular(8),
),
child: const Text('My Button'),
),
);
}
}