首页 > 解决方案 > 如何覆盖单个小部件的主题?

问题描述

我的 Flutter 应用程序的主题是在 TextFields 周围添加边框:

ThemeData(
    ...
    inputDecorationTheme: InputDecorationTheme(
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(width: 1.0),
        ),
        enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(width: 1.0),
        ),
    )

但是,我确实有一个不需要边框的 TextField,因此我尝试覆盖 TextField 中的边框:

TextField(
    decoration: InputDecoration.collapsed(
        hintText: _hintText,
        border: InputBorder.none,
      ),
    controller: _textController,
),

但我仍然得到边界?下面是部分图片。“请进!” 字段使用主题默认值,而“问题”字段是我试图覆盖的字段。

在此处输入图像描述

标签: fluttertextfield

解决方案


用Theme小部件包装您要覆盖的小部件,并为 data 属性放置一个新的 ThemeData 小部件。

return MaterialApp(
  theme: ThemeData(
    primarySwatch: Colors.orange,
    visualDensity: VisualDensity.adaptivePlatformDensity,
  ),
  home: Scaffold(
    body: Column(children: [
      TextFormField(), // Takes the theme of the overall MaterialApp
      Theme(
        data: ThemeData(
          primarySwatch: Colors.blue,
        ),
        child: TextFormField(), // Takes the theme of its direct parent
      ),
    ]),
  ),
);

这个基本示例只是改变颜色,所以使用你喜欢的任何 ThemeData。


推荐阅读