flutter开发实战-自定义长按TextField输入框剪切、复制、选择全部菜单AdaptiveTextSelectionToolba样式UI效果
在Flutter中,可以通过TextField
的toolbarOptions
属性来实现长按时弹出的系统菜单。但是,Flutter 目前不支持自定义这些系统菜单。因此,如果你想实现自定义的剪切、拷贝、选择全部等菜单项,你需要使用TextField
的onTap
回调来自己处理长按事件,并显示自定义的菜单。
以下是一个简单的示例,展示如何实现自定义的长按菜单:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: AdaptiveTextField(),
),
),
);
}
}
class AdaptiveTextField extends StatefulWidget {
@override
_AdaptiveTextFieldState createState() => _AdaptiveTextFieldState();
}
class _AdaptiveTextFieldState extends State<AdaptiveTextField> {
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
onTap: () {
showMenu(context: context, position: RelativeRect.fromLTRB(20, 20, 20, 20));
},
);
}
void showMenu({required BuildContext context, required RelativeRect position}) {
final RenderBox renderBox = context.findRenderObject()! as RenderBox;
final TextSelectionControls controls = MaterialTextSelectionControls();
final Matrix4 transform = renderBox.getTransformTo(null);
final Offset textFieldPos = transform.getTranslation();
final Rect textFieldRect = RelativeRect.fromLTRB(
textFieldPos.dx,
textFieldPos.dy,
textFieldPos.dx + renderBox.size.width,
textFieldPos.dy + renderBox.size.height,
).toRect(context.screen.size);
controls.getToolbar(
context,
_controller,
textFieldRect,
position,
).then((ToolbarOptions? options) {
if (options != null) {
showMenu<void>(
context: context,
items: <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: '复制',
child: Text('复制'),
),
const PopupMenuItem<String>(
value: '剪切',
child: Text('剪切'),
),
const PopupMenuItem<String>(
value: '选择全部',
child: Text('选择全部'),
),
],
).then((String? value) {
if (v
评论已关闭