Flutter
ModalBottomSheet
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'))]),
),
)
Exercise 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.
Show example 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');
}
Test yourself
-
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
Show answer
From the bottom of the screen — 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.
-
The showModalBottomSheet function
____(
context: context,
builder: (_) => SizedBox(height: 200, child: Text('Alt')),
);
Show answer
showModalBottomSheet(
context: context,
builder: (_) => SizedBox(height: 200, child: Text('Alt')),
);
-
ModalBottomSheet parts
- showModalBottomSheet
- Bottom sheet opening function
- context
- Context
- builder
- Content producing function
- SizedBox
- Height wrapper
Next lesson: Summary - Dialogs