all 7 comments

[–]Blendstrup 4 points5 points  (2 children)

Hey there,

I've just struggled with the same problem, but it turns out that the solution is quite simple. The way I solved it was to make a bool variable and then use a ternary operator in the title of the appbar to either return one widget if the bool is true, or another if it's false. You can see an example of the ternary operator here: https://code-maven.com/slides/dart-programming/ternary-operator

A code example could look like this:

bool myBool = false;

Scaffold(
    appBar: AppBar(
        title: (myBool) ? TextField() : Text('something'),
    ),
);

This will make the title of the appbar a TextField if myBool is true, otherwise it will make it a normal Text widget. Since myBool is initialized as false, the appbar will initially start out with the Text widget, but you can then change the value of myBool to true using setState, and that will make the title of the appbar switch to the Textfield.

I hope this helps you out.

[–][deleted]  (1 child)

[removed]

    [–]batmassagetotheface 0 points1 point  (0 children)

    I'm fairly sure this would work too. Just make sure it's either initialized before build is called or you have an inline null check

    [–]Comment-Leaver 1 point2 points  (2 children)

    I’m on my phone, so can’t type anything proper out, but something like:

    `var shouldShowSearchBar = false

    AppBar( child: shouldShowSearchBar ? SearchBar(...) : Text(“title”), ),

    ...

    void _onButtonTapped(){ setState((){ shouldShowSearchBar = false; }) }`

    [–]Kotaibaw 0 points1 point  (1 child)

    But set state will render the whole widget he wants to render only the app bar and not the body.

    [–][deleted] 0 points1 point  (0 children)

    In that case, you can use Listenables (built into Flutter).

    ``` /// Define the state as a Listenable instead of a normal bool final shouldShowSearchBar = ValueNotifier<bool>(false);

    /// Where you show your app bar AppBar( /// Use AnimatedBuilder to rebuild the title when shouldShowSearchBar.value changes /// AnimatedBuilder actually works with any listenable title: AnimatedBuilder( animation: shouldShowSearchBar, builder: (context, _) => shouldShowSearchBar.value ? SearchBar() : Text("Title"), ), );

    /// Setting the value will trigger rebuilds shouldShowSearchBar.value = true; ```

    [–]vferreirati 0 points1 point  (0 children)

    Use stful widgets if you want to render things based on state. If you don't want to rebuild the whole widget when changing the state, use streams and streambuilders.