【Flutter小技巧01】--- TextField文本垂直居中

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。

记录Flutter小技巧、踩坑、挖坑、重蹈覆辙、解决、清盘

相信大佬们在自定义搜索组件使用TextField组件的时候遇到文本不居中的问题,往往很多时候,看似简单的东西,花的时间缺最多,说实话,这个我花了不少时间 主要是因为固定了高度导致设置居中会失效

以下是未居中效果图:

image.png

以下是居中的效果图:

image.png

image.png

核心代码:

contentPadding:
    EdgeInsets.symmetric(vertical: -10, horizontal: -10),
border: OutlineInputBorder(borderSide: BorderSide.none),

复制代码

设置以上属性即可实现。

以下代码是参考网上设置的,但是不生效。

border: OutlineInputBorder( 
    borderSide: BorderSide( color: Colors.transparent, ), ),
    enabledBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.transparent, ), ),
    disabledBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.transparent, ), ), 
    focusedBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.transparent, ),
),
复制代码

居中完整代码:

TextField(
  controller: textEditingController,
  autofocus: true,
  textInputAction: TextInputAction.search,
  focusNode: focusNode,
  cursorColor: Color.fromRGBO(66, 133, 244, 1.0),
  // 对其 微调TextStyle的height 和 contentPadding
  style: TextStyle(
      height: 1.4, fontSize: 14, color: WMColor.text_373E4D),
  decoration: InputDecoration(
    icon: Padding(
      child: ImageWidget(
        WMImageName.patient_search,
        width: 18,
        height: 18,
        fit: BoxFit.contain,
      ),
      padding: EdgeInsets.only(left: 10),
    ),
    hintText: '输入关键词',
    hintStyle: TextStyle(
        height: 1.4, fontSize: 14, color: WMColor.text_A1A7B3),
    // contentPadding:
    //     EdgeInsets.symmetric(vertical: -10, horizontal: -10),
    border: OutlineInputBorder(borderSide: BorderSide.none),
    counterText: "",
  ),
  textAlignVertical: TextAlignVertical.center,
  onSubmitted: (vale) {
    if (searchCallBack != null) {
      searchCallBack!(vale);
    }
  },
  onChanged: (vale) {
    if (onChanged != null) {
      onChanged!(vale);
    }
  },
),
复制代码

以上就是记录小技巧01,如有不对的地方,大佬们多多指点。

猜你喜欢

转载自juejin.im/post/7013631222836363277