我想为文本字段提供一个初始值,并重新绘制一个空值以清除文本。用Flutter的api实现这一点的最佳方法是什么?


当前回答

你可以使用TextFormField代替TextField,并使用initialValue属性。例如

TextFormField(initialValue: "I am smart")

其他回答

你不需要在小部件范围内定义一个单独的变量,只需内联即可:

TextField(
  controller: TextEditingController()..text = 'Your initial value',
  onChanged: (text) => {},
)

如果您使用文本表单字段并将数据从上一页传递到下一页文本表单字段,请使用此选项

class ProfilePage extends StatefulWidget {

  late final String fname;

    ProfilePage({required this.fname});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final _form = GlobalKey<FormState>();
  
  late var FullNameController = TextEditingController(text: widget.fname);
  
}

(来自邮件列表。这个答案不是我想出来的。)

class _FooState extends State<Foo> {
  TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = new TextEditingController(text: 'Initial value');
  }

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[
        new TextField(
          // The TextField is first built, the controller has some initial text,
          // which the TextField shows. As the user edits, the text property of
          // the controller is updated.
          controller: _controller,
        ),
        new RaisedButton(
          onPressed: () {
            // You can also use the controller to manipuate what is shown in the
            // text field. For example, the clear() method removes all the text
            // from the text field.
            _controller.clear();
          },
          child: new Text('CLEAR'),
        ),
      ],
    );
  }
}

你可以使用TextFormField代替TextField,并使用initialValue属性。例如

TextFormField(initialValue: "I am smart")

如果你想处理多个textinput,因为@MRT在接受的答案的评论中要求,你可以创建一个函数,接受一个初始值,并返回一个TextEditingController,像这样:

initialValue(val) {
  return TextEditingController(text: val);
}

然后,将这个函数设置为TextInput的控制器,并像这样提供它的初始值:

controller: initialValue('Some initial value here....')

您可以为其他textinput重复此操作。