Home > Software engineering >  How can i change app bar text to TextField in flutter with a icon buton?
How can i change app bar text to TextField in flutter with a icon buton?

Time:02-11

I'm making an app to search courses on firebase. The app bar shows a text: "Home", and it has a search button at the rigth side of the screen:

enter image description here

I want to hide that "Home" text from de app bar at moment to click the search button, and show the field to type the query.

this is my code, i dont know how to implement that.

appBar: AppBar(
    title: Text(
      "Home",
      style: TextStyle(
        fontSize: 16.0, /*fontWeight: FontWeight.bold*/
      ),
    ),
    centerTitle: true,

 //search icon
 actions: [
  IconButton(
    icon: Icon(Icons.search),
    onPressed: () {
      //i want to change the text of the app bar:"Home" to a TextField to type
      AppBar(
        title: TextField(
          style: TextStyle(color: Colors.white),
          decoration: InputDecoration(
              hintText: 'Search Courses',
              hintStyle: TextStyle(color: Colors.white)),
          controller: searchController,
        ),
      );
    },
  ),
],

),

CodePudding user response:

You can use a boolean variable that tells is searching or not.

bool isSearching = false;

appBar: AppBar(
    title: isSearching ? TextField(
          style: TextStyle(color: Colors.white),
          decoration: InputDecoration(
              hintText: 'Search Courses',
              hintStyle: TextStyle(color: Colors.white)),
          controller: searchController,
) 

     : Text(
      "Home",
      style: TextStyle(
        fontSize: 16.0, /*fontWeight: FontWeight.bold*/
      ),
    ),
    centerTitle: true,

 //search icon
 actions: [
  IconButton(
    icon: Icon(Icons.search),
    onPressed: () {
      setState((){
        isSearching = true;
      });
    },
  ),
],

),

CodePudding user response:

I think you want something like this:

  bool _showSearch=false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _showSearch? TextField(
          controller: searchController,
          style: const TextStyle(color: Colors.white),
          decoration: const InputDecoration(
              hintText: 'Search Courses',
              hintStyle: TextStyle(color: Colors.white)),
        ):const Text(
          "Home",
          style: TextStyle(
            fontSize: 16.0, /*fontWeight: FontWeight.bold*/
          ),
        ),
        centerTitle: true,

        //search icon
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              setState(() {
                _showSearch=!_showSearch;
              });
            },
          ),
        ],
      ),
    );
  }
  • Related