DraggableScrollableSheet child starts in the middle of the sheet in flutter

Viewed 154

I have a listview in the main scaffold, and I added a gesturedetector in the items to display a bottomsheet for item details. The issue is that the content starts in the middle of the sheet.

this is how the code for the sheet:

showModalBottomSheet(
    context: context,
    builder: (context) => SizedBox.expand(
      child: DraggableScrollableSheet(
        builder: (BuildContext context, ScrollController scrollController) {
          return Container(
            color: Colors.red,
            child: ListView.builder(
              itemCount: 2,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(title: Text('text'));
              },
            ),
          );
        },
      ),
    ),
  );

How can I make the contents of the sheet to start at the top? I have tried enclosing the listview with Align class and set the alignment to topcenter but same result.

enter image description here

1 Answers

You should remove your SizedBox and pass in expand: false to fix your immediate problem.

In addition, if you want a ListView to scroll with the DraggableScrollableSheet, you need to set isScrollControlled: true, and pass the controller to ListView as well.

Here is a full example of using a ListView as child:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyHome()));
}

class MyHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('BottomSheet Demo')),
      body: Center(
        child: ElevatedButton(
          child: Text('Show DraggableScrollableSheet'),
          onPressed: () async {
            final result = await showModalBottomSheet(
              context: context,
              isScrollControlled: true,
              builder: (_) => DraggableScrollableSheet(
                expand: false,
                builder: (context, ScrollController controller) {
                  return ListView.builder(
                    controller: controller,
                    itemCount: 100,
                    itemExtent: 50,
                    itemBuilder: (context, index) {
                      return Center(child: Text('Item $index'));
                    },
                  );
                },
              ),
            );
            print(result);
          },
        ),
      ),
    );
  }
}
Related