Why does Sliver App Bar's flexibleSpace parameter have to take a Widget with a const constructor?

Issue

I am trying to build a custom scroll view which contains a sliver app bar to achieve something similar to what’s shown here:

https://medium.com/@diegoveloper/flutter-collapsing-toolbar-sliver-app-bar-14b858e87abe

However I want to have the word Search and below it I want 3 IconButtons Evenly spaced, when the page (CustomScrollView) is scrolled, I want the 3 IconButtons to be pinned to the top of the SliverAppBar and the Search Text to disappear…

I Tried to achieve the above via the following code:

 class SearchPage extends StatelessWidget {

      const SearchPage();

      @override
      Widget build(BuildContext context) {
        return CustomScrollView(slivers: <Widget>[
        const SliverAppBar(
        pinned: true,
            expandedHeight: 250.0,
            flexibleSpace: _buildSliverAppBarFlex(),
            );
      }


       Widget _buildSliverAppBarFlex() {
        return Container(
            child: Column(
              children: <Widget>[
                Text("Search", style: TextStyle(fontSize: 24.0,
                    color: Colors.white,
                    fontWeight: FontWeight.bold)),
                Row(children: <Widget>[
                  IconButton(icon: Icon(Icons.flight)),
                  IconButton(icon: Icon(Icons.hotel)),
                  IconButton(icon: Icon(Icons.drive_eta))
                ])
              ],
            )
        );
      }
    }

However I get a warning that flexibleSpace must take a const constructor widget and that the _buildSilverAppBarFlex Widget I’ve made is not – I cannot add const or final to it either… Any ideas how I can achieve what I want?

Solution

The warning comes because you are using const ahead of your SliverAppBar, remove this, and warning will be gone.

So, instead of this

const SliverAppBar(...)

Use this.

SliverAppBar(...)

If you want to use const there, make sure your FlexibleSpaceBar is also a const then.

Answered By – CopsOnRoad

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.