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

Flutter如何让TextField使用时样式不变仅显示光标

Flutter TextField激活/未激活样式一致性解决方案

问题原因

当前代码仅为TextField配置了非激活状态下的边框样式enabledBorder,未配置聚焦激活状态的focusedBorder属性,当TextField获得焦点时会默认使用App主题的边框样式,因此出现两种状态下的外观差异。

解决方案

在InputDecoration配置项中,新增与enabledBorder完全一致的focusedBorder配置即可。如果后续需要适配禁用、错误提示等场景的样式一致性,也可以同步配置disabledBorder、errorBorder属性,保持所有状态下的边框配置相同。

核心修改代码(TextField部分)

TextField(
  onChanged: (value) {},
  decoration: InputDecoration(
    // 非激活状态边框
    enabledBorder: OutlineInputBorder(
        borderSide: const BorderSide(color: Colors.white, width: 0.0),
        borderRadius: BorderRadius.circular(20.0)
    ),
    // 新增:聚焦激活状态边框,和非激活配置完全一致
    focusedBorder: OutlineInputBorder(
        borderSide: const BorderSide(color: Colors.white, width: 0.0),
        borderRadius: BorderRadius.circular(20.0)
    ),
    fillColor: Colors.white,
    filled: true,
    hintText: "Search",
    hintStyle: TextStyle(
      color:  Colors.grey.withOpacity(0.5),
    ),
  ),
)

完整可运行代码

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Shop App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage() ,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key,}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Center(
        child: 
        Padding(
          padding: EdgeInsets.all(25.0),
          child: TextField(
            onChanged: (value) {},
            decoration: InputDecoration(
              enabledBorder: OutlineInputBorder(
                borderSide: const BorderSide(color: Colors.white, width: 0.0),
                borderRadius: BorderRadius.circular(20.0)
              ),
              // 新增聚焦状态边框配置
              focusedBorder: OutlineInputBorder(
                borderSide: const BorderSide(color: Colors.white, width: 0.0),
                borderRadius: BorderRadius.circular(20.0)
              ),
              fillColor: Colors.white,
              filled: true,
              hintText: "Search",
              hintStyle: TextStyle(
                color:  Colors.grey.withOpacity(0.5),
              ),
            ),
          ),
        )
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:15:07