Ian Rehwinkel
Ian Rehwinkel

Reputation: 2615

Smoothly transition states in Flutter

I'm switching between two states. One being the default app bar, and the other being the search app bar. What I am asking is, how I can make that transition smooth, because at the moment, it instantly jumps from one state to the other and looks pretty disruptive. This is my code:

@override
Widget build(BuildContext context) {
    var appBar;
    if(isSearching){
        appBar = AppBar(
            title: Text("SEARCH"),
            leading: IconButton(
                onPressed: (){
                        stopSearch();
                    },
                icon: Icon(Icons.arrow_back),
            ),
        );
    }else{
        appBar = AppBar(
            title: Text(widget.title),
            actions: <Widget>[
                IconButton(
                    onPressed: (){
                        startSearch();
                    },
                    icon: Icon(Icons.search, color: Colors.white,),
                ),
            ],
        );
    }

    return Scaffold(
        appBar: appBar,
        body: ListView(
            children: <Widget>[
                Text("PETER"),
                Text("PETER"),
                Text("PETER"),
                Text("PETER"),
            ],
        ),
    );
}

I want it to be like on the Material design docs: https://material.io/design/navigation/search.html#expandable-search

Upvotes: 2

Views: 2950

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 276951

You can use AnimatedCrossFade to have a fade animation between two widget

AppBar(
  title: AnimatedCrossFade(
    duration: Duration(milliseconds: 250),
    firstChild: Text("Title"),
    secondChild: TextField(),
    alignment: Alignment.centerLeft,
    layoutBuilder: (w1, _, w2, __) {
      return Container(
        height: 43.0,
        width: double.infinity,
        child: Stack(
          alignment: Alignment.centerLeft,
          children: <Widget>[w1, w2],
        ),
      );
    },
    crossFadeState:
        !searching ? CrossFadeState.showSecond : CrossFadeState.showFirst,
  ),
)

Upvotes: 7

Related Questions