如何在Flutter中在应用栏中添加文本输入框?

10

我在将TextField放置在AppBar上遇到了问题,以便用户可以输入内容,类似于使用搜索栏。我需要获取用户输入并对其执行某些操作,因此这不是我的应用程序内部的搜索。这就是为什么使用TextField是有意义的。

现在,我已成功将TextField放置在我的AppBar左侧。问题是TextField是一个正方形,不占据足够的空间,因此您无法看到自己正在编写的内容。

链接指向它的外观:

The search bar visually

以下是代码实现:

 @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Myseum',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'Raleway',
      ),
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            "Myseum",
            style: TextStyle(
              fontFamily: 'Raleway',
              fontStyle: FontStyle.italic,
              fontSize: 25,
            ),
          ),
          leading: prefix0.TextBox(), // TextBox is the widget I made.
          backgroundColor: Colors.black,
        ),


现在小部件是TextBox()

class TextBox extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      color: Colors.white,
      child: TextField(
        decoration:
            InputDecoration(border: InputBorder.none, hintText: 'Search'),
      ),
    );
  }
}


有很多关于搜索栏的软件包可以在您的项目中使用,或者作为构建自己的搜索栏指南:https://pub.dev/flutter/packages?q=searchbar - diegoveloper
我不想建立一个搜索栏。我想在我的应用程序栏中放置一个文本字段。 - WindBreeze
3
将您的文本字段放置在 title 组件中。 - diegoveloper
1个回答

12

就像评论中提到的那样-将您的文本字段放在标题小部件中...我将您的代码转换为一个简单的有状态小部件,以便让您有个想法。

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool typing = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: typing ? TextBox() : Text("Title"),
        leading: IconButton(
          icon: Icon(typing ? Icons.done : Icons.search),
          onPressed: () {
            setState(() {
              typing = !typing;
            });
          },
        ),
      ),
      body: Center(
        child: Text("Your app content"),
      ),
    );
  }
}

class TextBox extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      color: Colors.white,
      child: TextField(
        decoration:
            InputDecoration(border: InputBorder.none, hintText: 'Search'),
      ),
    );
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接