如何在 Flutter 的应用栏中添加文本字段?

Win*_*eze 5 textfield dart flutter flutter-appbar

我在TextField打开时遇到问题,AppBar因此用户可以输入类似于使用搜索栏的输入。我需要接受用户输入并用它做一些事情,所以它不是我的应用程序中的搜索。这就是为什么使用TextField.

现在,我已经成功地在TextField我的AppBar. 问题是它TextField是一个正方形并且不占用足够的空间所以你可以看到你在写什么。

链接到它的外观:

视觉上的搜索栏

在代码中,这是如何制作的:

 @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,
        ),


Run Code Online (Sandbox Code Playgroud)

现在小部件 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'),
      ),
    );
  }
}

Run Code Online (Sandbox Code Playgroud)

Xan*_*che 6

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

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'),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)