flutter textfield內容不居中問題


在使用TextField的時候如果設置了textField高度,容易導致內容無法居中的問題,剛開始使用的contentPadding,設置內容上下便宜的padding來控制內容居中,這種方式能達到效果,但是在部分小屏手機上還是會出現不居中的情況,如圖所示

安卓的機型更多,如果都要做適配,那將是及其困難的事情

在網上也看了一些其他的解決方案
https://github.com/flutter/flutter/issues/40248
通過設置 textBaseline: TextBaseline.alphabetic 來實現內容居中,設置了一番 發現並沒有達到理想的效果

這里推薦一種確實有效的方法,來解決TextField內容居中的問題
我們通常在使用textField的時候默認將其border設置為 InputBorder.none,如果我們給textField設置外邊框,你會發現,內容竟然居中了

由此可見,當我們給textField設置了外邊框,textField的內容就會居中顯示,那么剩下的問題就簡單了,將外邊框設置為透明色即可

            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,
                      ),
                    ),

有一點很重要 contentPadding一定要設置上下邊距為0

contentPadding: EdgeInsets.only(top: 0, bottom: 0)

以上就是能夠確保textField內容能夠完美居中的解決方案

1.設置textField有邊框,並設置外邊框為透明色
2.設置contentPadding:EdgeInsets.only(top: 0, bottom: 0)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM