'How to dynamically change the bottomsheet height based on the lenght of the list in flutter

I have to use showModalBottomSheet for displaying list of menu item. But I am unable to dynamically set the height of the bottomsheet. Please help me to solve this issue. Thankyou.



Solution 1:[1]

This is how you can dynamically change the bottomsheet height based on the length of the list in the bottom sheet. But be aware of that you need to use statefulbuilder in the showModalBottomSheet to be able to setState the list.

List<int> myList = [1,2,3,4,5,6];
  @override
  Widget build(BuildContext context) {
    
    return  Center(
      child: ElevatedButton(
        child: const Text('showModalBottomSheet'),
        onPressed: () {
          showModalBottomSheet<void>(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
              builder: (context, _setState){
                return Container(
                height: myList.length * 100,
                color: Colors.amber,
                child: ListView.builder(
                      itemCount: myList.length,
                      itemBuilder: (BuildContext ctxt, int index) {
                       return Row(
                       children: [
                         Text(myList[index].toString()),
                         TextButton(
                            onPressed: () {
                                _setState((){
                                  myList = myList.where((value) => value != myList[index]).toList();
                         
                                });
                            },
                            child: Text("delete"),
                            )
                       ]);
                      }
                    )
              );
              }
                
              );
            },
          );
        },
      ),
    );
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Timur Turbil