You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何修改文本输入框选中状态的光标颜色?

解决方案

你当前仅配置了cursorColor属性,该属性仅控制输入时的普通闪烁光标颜色,选中文本后的选择手柄(即你需要修改的圈出部分)、选中文本的背景色,需要通过ThemeData下的textSelectionTheme属性配置:

  • 选择手柄颜色对应selectionHandleColor参数
  • 选中文本的背景色对应selectionColor参数

你只需在现有代码的ThemeData中新增对应配置即可,修改后的代码如下:

Padding(
  padding: const EdgeInsets.fromLTRB(40, 8, 40, 20),
  child: Theme(
    data: new ThemeData(
      primaryColor: Colors.red,
      accentColor: Colors.orange,
      hintColor: Colors.white,
      // 新增文本选择主题配置
      textSelectionTheme: TextSelectionThemeData(
        cursorColor: Colors.white, // 普通光标颜色也可以统一放到这里配置
        selectionColor: Colors.white.withOpacity(0.3), // 选中文本的背景色,可根据需求调整透明度
        selectionHandleColor: Colors.white, // 你要修改的选择手柄颜色
      ),
      inputDecorationTheme: new InputDecorationTheme(
          labelStyle: new TextStyle(color: Colors.red)),
    ),
    child: TextFormField(
      textInputAction: TextInputAction.next,
      // 这里的cursorColor如果上面已经配置就可以删掉,优先级以TextFormField的配置为准
      cursorColor: Colors.white,
      controller: nameController,
      keyboardType: TextInputType.name,
      textAlign: TextAlign.center,
      enabled: isNameEdit,
      focusNode: focusNode,
      decoration: InputDecoration(
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white, width: 2),
        ),
      ),
      style: TextStyle(
          fontSize: t1Size,
          color: Colors.white,
          fontWeight: FontWeight.w700),
    ),
  ),
)

如果需要全局生效,直接把上述textSelectionTheme配置放到项目根MaterialApp的theme属性中即可,不需要给每个输入框单独包裹Theme组件。

内容的提问来源于stack exchange,提问作者Deepak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:06:03