设置所选文本的颜色

斯普林兹

我正在为我的应用程序设置主题,我想使用简约的黑白调色板。为此,我希望文本在正常状态下看起来是黑色的,而在选择颜色为黑色的情况下选择它时,它看起来是白色的。

到目前为止,我已经找到了一种将选择颜色设置为黑色的方法,但现在它只是与文本混合,因为所选文本的颜色也保持黑色。有没有办法设置所选文本的颜色?

TemeData(
  textSelectionTheme: TextSelectionThemeData(
    cursorColor: Colors.black,
    selectionColor: Colors.black,
  ),
);

我想要的是:

我想要的是

恩佐

我在 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章