Flutter - SingleChildScrollView fixed widget

Massimo Caroccia picture Massimo Caroccia · Jan 16, 2020 · Viewed 8.6k times · Source

there is an ability to have a SingleChildScrollView into a Scaffold that have another widget over the SingleChildScrollView that does not need to be scrolled. For example I've a SingleChildScrollView and I need to add a fixed button into a specified position, but this button does not to be scrolled.

I try with a Stack widget but if I add a button widget before the SingleChildScrollView this is not be able to be clicked otherwise if I add the button after the SingleChildScrollView the scroll touch does not work.

Anyone have some problem?

Answer

João Soares picture João Soares · Jan 16, 2020

Now that we understand what you want to achieve, it can be done with a Stack widget, a ListView and using an Align widget to position the Container that holds the widget you want to use as a title:

Stack(
  children: <Widget>[
    ListView.builder(
      itemCount: 20,
      itemBuilder: (context, index) {
        return Container(
          child: Text('item $index'),
          height: 40,
          color: Colors.blueGrey,
          margin: EdgeInsets.all(14),
        );
      }
    ),
    Align(
      alignment: Alignment.topCenter,
      child: Container(
        margin: EdgeInsets.only(top: 20),
        alignment: Alignment.center,
        height: 30,
        width: 300,
        color: Colors.blue,
        child: Text('This is a title')
      ),
    ),
  ],
)

Previous answers before finally understanding what the user wanted.

If I understood your issue correctly and you want within a view to have a fixed Widget at the top and a list of scrollable items below it, then a CustomScrollView with a SliverAppBar and a SliverList would be the solution for you. Please see the example below:

CustomScrollView(
  slivers: <Widget>[
    SliverAppBar(
      pinned: true,
      title: Center(child: Text('Title')),
    ),
    SliverList(
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          return Container(
            height: 40,
            margin: EdgeInsets.all(10),
            alignment: Alignment.center,
            color: Colors.teal[100 * (index % 9)],
            child: Text('grid item $index'),
          );
        },
        childCount: 20
      ),
    ),
  ],
)

If you want the fixed Widget to be at the bottom of the view, you can use the bottomNavigationBar property of the Scaffold`:

Scaffold(
  ...
  bottomNavigationBar: Container(
    alignment: Alignment.center,
    height: 50,
    child: Text('title')
  ),
)