ModalBottomSheet
- Flutter course
- Intermediate
- Lesson 94/99
- 4 min
Open a bottom sheet with showModalBottomSheet.
What is showModalBottomSheet?
showModalBottomSheet shows a sheet sliding up from the bottom of the screen. It takes context and builder parameters; like showDialog, it is modal. The user can close the sheet by dragging it down; therefore visual cues like a dragHandle are commonly used.
showModalBottomSheet(
context: context,
builder: (context) {
return SizedBox(height: 200, child: Text('Alt sayfa'));
},
);Builder and size
The widget returned by showModalBottomSheet's builder sets the sheet's content. Its height depends on this widget's size; for example SizedBox(height: 200) gives a fixed height. If the content needs to scroll you use ListView or SingleChildScrollView.
showModalBottomSheet(
context: context,
builder: (_) => SizedBox(
height: 250,
child: ListView(children: [ListTile(title: Text('A'))]),
),
)Practice Open a bottom sheet
Define a StatelessWidget named AltSayfaButon. Its build should return an ElevatedButton whose onPressed calls showModalBottomSheet. Provide the context and builder parameters; builder should return a SizedBox(height: 200, child: Text('Alt sayfa')). Print 'hazir' in main.
Starter code
import 'package:flutter/material.dart';
// AltSayfaButon StatelessWidget tanımla
// build ElevatedButton döndürsün
// onPressed alt sayfa açsın
void main() {
// 'hazir' yazdır
}Sample solution
import 'package:flutter/material.dart';
class AltSayfaButon extends StatelessWidget {
const AltSayfaButon({super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
showModalBottomSheet(
context: context,
builder: (_) => const SizedBox(
height: 200,
child: Text('Alt sayfa'),
),
);
},
child: const Text('Aç'),
);
}
}
void main() {
print('hazir');
}Expected output
hazir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where does showModalBottomSheet open the sheet from?
- From the top of the screen
- From the side menu
- From the center of the screen
- From the bottom of the screen Correct answer
Explanation: showModalBottomSheet slides up from the bottom of the screen. There is no top opening, side menu is Drawer's job, and center opening is for showDialog/AlertDialog.
2 The showModalBottomSheet function
____(
context: context,
builder: (_) => SizedBox(height: 200, child: Text('Alt')),
);
showModalBottomSheet(
context: context,
builder: (_) => SizedBox(height: 200, child: Text('Alt')),
);
Explanation: To open a bottom sheet you use showModalBottomSheet. showDialog opens a center dialog, there is no function called showSnackBar (showSnackBar is deprecated), and there is no showDrawer function.
3 ModalBottomSheet parts
| Term | Meaning |
|---|---|
showModalBottomSheet |
Bottom sheet opening function |
context |
Context |
builder |
Content producing function |
SizedBox |
Height wrapper |