Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a texfield inside the App bar in Flutter?

I'am having trouble in having a TextField on the AppBar so the user can enter input similarly to using a search bar. I need to take the user input and do something with it so it's not a search within my app. This is why it makes senses to use a TextField.

Now, I've succeeded in having the TextField on the left side of my AppBar . The problem is that the TextField is a square and doesn't take enough space so you can see what you're writing.

Link to what it looks like:

The search bar visually

In code this is how it was made:

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


Now the widget 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'),
      ),
    );
  }
}

like image 230
WindBreeze Avatar asked May 28 '19 16:05

WindBreeze


1 Answers

Like mentioned in the comments - put your text field in title widget... I converted your code to a simple stateful widget to give you an idea.

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'),
      ),
    );
  }
}
like image 162
Xander Terblanche Avatar answered Nov 15 '22 06:11

Xander Terblanche