【问题标题】:Displaying actual value in TextFormField and InputDecoration在 TextFormField 和 InputDecoration 中显示实际值
【发布时间】:2021-08-05 20:08:07
【问题描述】:

有没有办法简单地将hintText 转换为实际值?我从另一个类(一个人输入给定值的上一个屏幕)获得 ${widget.message},然后希望它被硬编码。我尝试在 TextFormField 中使用 initialValue,但无法正常工作。

在编写 initialValue: ${widget.message} 时,在控制器之前,我得到“Failed assertion: line 196 pos 15: 'initialValue == null || controller == null': is not true。”

               TextFormField(
                controller: nameController,
                validator: (value){
                  if(value.isEmpty){
                    return "Enter Valid Name";
                  }else{
                    return null;
                  }
                },
                decoration: InputDecoration(
                  hintText: "${widget.message}",
                  suffixIcon: IconButton(
                    onPressed: () => nameController.clear(),
                    icon: Icon(Icons.clear),
                  ),
                ),
              ),

【问题讨论】:

  • 没有控制器:stackoverflow.com/a/51382431/2252830,如果你已经有一个控制器,只需使用它的text 属性
  • 我需要控制器,因为它会进一步发送数据。试过 TextEditingController nameController = TextEditingController(text: "${widget.message}"); ,但也不起作用。
  • 我按照上面写的例子做了。

标签: flutter


【解决方案1】:

创建一个TextEditingController 并在initState 中为其提供'${widget.message}' 值,然后通过设置属性enabled: false 禁用TextFormField。

例如:

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key key, this.message}) : super(key: key);
  final String message;

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

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  final text = TextEditingController();

  @override
  void initState() {
    super.initState();
    text.text = '${widget.message}'; //provide the controller the recived value in initState
  }

  @override
  void dispose() {
    text.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: TextFormField(
            controller: text,
            enabled: false, //Set it to false so they can't further change it
            decoration: InputDecoration(
              border: OutlineInputBorder(),
            ),
          ),
        ),
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2019-09-05
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多