flutter textField设定高度后,文字无法居中

问题:

如果给textField设定的布局高度大于或小于它的默认高度,那么它的居中就会有问题.

主要在于

border 不能直接使用InputBorder.none

1. contentPadding: EdgeInsets.all(0);(一般只设置这一个就居中显示了)

2.如果文字偏上用TextAlignVertical.bottom修正

3.也可以使用isCollapsed: true,来修正(不一定起作用)

// ignore_for_file: prefer_const_constructors

import 'package:flutter/material.dart';
// import 'package:oil_enterprise/common/widgets/widgets.dart';

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

  @override
  _DemoState createState() => _DemoState();
}

class _DemoState extends State {
  late TextEditingController _controller;

  FocusNode focusNode = FocusNode();

  String inputText = '1234';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      FocusScope.of(context).requestFocus(focusNode);
    });
    _controller = TextEditingController.fromValue(TextEditingValue(
        text: inputText,
        selection: TextSelection.fromPosition(TextPosition(
            offset: inputText.length, affinity: TextAffinity.upstream))));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SizedBox(
            height: 50,
            width: 200,
            child: TextField(
                style: TextStyle(color: Colors.black, fontSize: 16),
                autofocus: true,
                controller: _controller,
                cursorColor: Colors.deepOrange,
                cursorWidth: 1,
                onChanged: (value) {
                  inputText = value;
                  setState(() {});
                },
                decoration: InputDecoration(
                    // isCollapsed: true,
                    contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                    fillColor: Colors.green,
                    filled: true,
                    hintText: "请输入...",
                    hintStyle: TextStyle(color: Colors.red),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                        borderSide: BorderSide(color: Colors.blue, width: 1)),
                    suffixIcon: inputText.isNotEmpty
                        ? GestureDetector(
                            onTap: () {
                              _controller.clear();
                              inputText = '';
                              setState(() {});
                            },
                            child: Icon(Icons.close))
                        : Text('')))),
      ),
    );
  }
}

你可能感兴趣的:(flutter,ios)