Flutter SelectionArea 简单使用
Flutter SelectionArea的文本选择功能简单介绍
·
SelectionArea

SelectionArea 是Flutter 3.3新增的一个文本选择功能控件。
其属性有
const SelectionArea({
super.key,
this.focusNode,
this.selectionControls,
required this.child,
});
focusNode 焦点
selectionControls 选择文本的样式
例如:根据不同平台设置样式
switch (Theme.of(context).platform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
controls = materialTextSelectionControls;
break;
case TargetPlatform.iOS:
controls = cupertinoTextSelectionControls;
break;
case TargetPlatform.linux:
case TargetPlatform.windows:
controls = desktopTextSelectionControls;
break;
case TargetPlatform.macOS:
controls = cupertinoDesktopTextSelectionControls;
break;
}
SelectionArea 的使用十分简单,只需要在您想要支持的地方添加 SelectionArea 即可,甚至可以在每个路由下的 Scaffold 添加 SelectionArea 来全面启用支持。
例如:
body: SelectionArea(
focusNode: FocusNode(),
selectionControls: controls!,
child: Text(text),
),
默认情况下 SelectionArea 已经实现了所有常见的功能,并且 Flutter 针对不同平台进行了差异化实现,如下图所示 Android 和 iOS 会有不同的样式效果。
图1 iOS
|
图2 Android
|
iOS的Toolbar 居然没有全选,其实这是因为 iOS 使用了 TextSelectionControls 默认的 canSelectAll 判断,这个判断里有一个条件就是需要 selection 的 start == end 才符合条件。
bool canSelectAll(TextSelectionDelegate delegate) {
return delegate.selectAllEnabled && delegate.textEditingValue.text.isNotEmpty && delegate.textEditingValue.selection.isCollapsed;
}
delegate.textEditingValue.selection.isCollapsed的start == end
如果您觉得这个判断有问题,完全可以自己 override 一个自定义的 TextSelectionControls,比如在 canSelectAll 直接 return true。即可实现iOS显示全选按钮
@override
bool canSelectAll(TextSelectionDelegate delegate) {
return true;
}
也可以直接继承TextSelectionControls,在实现的方法里面改写;
链接: demo地址(https://github.com/Iamhopemiracle/function_project).
更多推荐
图1 iOS
图2 Android



所有评论(0)