如何在 Flutter 中创建全屏 TextField

Ale*_*ink 9 dart flutter

我尝试构建一个聊天应用程序,其中“新消息”屏幕包含收件人和消息。我希望 TextField 填满屏幕上的剩余空间。就像 HTML 中的 Textarea 一样。

  1. 我尝试将 增加到maxLines一个很大的数字,这导致浮动操作按钮出现像素溢出错误。
  2. 我尝试将它包装在一个Expanded小部件中,但这对它没有任何影响。

这是我当前的布局结构:

    body: new Column(
        children: <Widget>[
          new ListTile(
            dense: false,
            title: new Text("Alex XYZ",
                //...
          ),
          Divider(),
          new TextField(
              decoration: InputDecoration(hintText: "Insert your message",),
              scrollPadding: EdgeInsets.all(20.0),
              autofocus: true,
          )
        ],
      ),
Run Code Online (Sandbox Code Playgroud)

使用上面代码中的 TextField 我什至无法编写多行。如果我添加 maxLines: 2 我可以按 Enter 向下移动,但这看起来不干净,并且您无法在该区域滚动。

我希望有人能帮助我如何将其扩展到整个屏幕。

最好的问候亚历克斯!

Man*_*aul 8

任何在 2021 年 1 月及此后阅读本文的人......

Expanded()小部件将为您提供帮助

就像这样把你包裹起来TextField()......Expanded()

Expanded(
    child: TextField(
              decoration: InputDecoration(hintText: "Insert your message",),
              scrollPadding: EdgeInsets.all(20.0),
              autofocus: true,
          )
)
Run Code Online (Sandbox Code Playgroud)

这将考虑剩余的屏幕并像一个巨人一样对待TextField()

另外,如果您想删除 TextField 的下划线(我认为这对于此类应用程序是必要的),请使用collapsed()InputDecoration 类的构造函数,如下所示

InputDecoration.collapsed()
Run Code Online (Sandbox Code Playgroud)

注意:我想将其添加为原始问题的评论,但由于声誉较低而无法这样做。


and*_*oid 6

现在您可以使用 maxline 99999,因为如果我们在 maxline 中传递 double.infinity.toInt() 以获得无限行,那么 flutter 中已经存在未解决的问题。

因此,要创建具有滚动功能的多行文本视图,您可以将 maxline 99999 与 SingleChildScrollView 小部件一起使用,如下所示。它将允许您滚动以及 maxline。

如果您使用如下示例,它也将适合屏幕:

return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextField(
                decoration: InputDecoration(hintText: "Insert your message",),
                scrollPadding: EdgeInsets.all(20.0),
                keyboardType: TextInputType.multiline,
                maxLines: 99999,
                autofocus: true,)
            ],
          ),
        ),
      ),
      resizeToAvoidBottomPadding: true,
    );
Run Code Online (Sandbox Code Playgroud)

  • tru 使用我的代码它不会给你带来像素溢出问题,如果它仍然给你带来问题,那么你可以在脚手架中使用“resizeToAvoidBottomPadding:true” (2认同)