我在 Flutter 库中没有找到任何东西,但是你可以尝试使用这个 Widget:
class SelectableColoredText extends StatefulWidget {
final String text;
final TextStyle? style;
final Color selectedColor;
final Color selectedBackgroundColor;
const SelectableColoredText(this.text, {
Key? key,
this.style,
required this.selectedColor,
required this.selectedBackgroundColor,
}) : super(key: key);
@override
_SelectableColoredTextState createState() => _SelectableColoredTextState();
}
class _SelectableColoredTextState extends State<SelectableColoredText> {
int? _start;
int? _end;
@override
Widget build(BuildContext context) {
final int start = _start ?? widget.text.length;
final int end = _end ?? widget.text.length;
return SelectableText.rich(
TextSpan(
style: widget.style ?? Theme.of(context).textTheme.bodyText2,
children: [
// Text before the selection
TextSpan(text: widget.text.substring(0, start)),
// Selected text
TextSpan(
text: widget.text.substring(start, end),
style: TextStyle(
color: widget.selectedColor,
backgroundColor: widget.selectedBackgroundColor,
),
),
// Text after the selection
TextSpan(text: widget.text.substring(end, widget.text.length)),
],
),
// Update the start and end positions of the selection
onSelectionChanged: (selection, _) {
final int newStart = min(selection.baseOffset, selection.extentOffset);
final int newEnd = max(selection.baseOffset, selection.extentOffset);
if (_start == newStart && _end == newEnd) return;
setState(() {
_start = newStart;
_end = newEnd;
});
},
);
}
}
你可以这样使用它:
SelectableColoredText(
'The quick brown fox jumps over the lazy dog',
// The default text style
style: TextStyle(fontSize: 40, color: Colors.black),
// The color of the selected text
selectedColor: Colors.white,
// The background color of the selected text
selectedBackgroundColor: Colors.black,
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句