Here you have Simple Example of how to use a Modal Bottom Sheet in Flutter. It is common user experience pattern – to put important items on the bottom side of the screen. The idea is the items to be accessible to your fingures while using your device with a single hand.
Modal Bottom Sheet in Flutter Code
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Modal Bottom Sheet Example',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
void _showModalBottomSheet(BuildContext context) => showModalBottomSheet(
context: context,
isDismissible: false,
builder: (BuildContext context) {
return SizedBox(
height: 120,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('This is a modal bottom sheet'),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FilledButton(
onPressed: () {
debugPrint("Confirm");
Navigator.of(context).pop();
},
child: const Text('Confirm'),
),
const SizedBox(
width: 30,
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
),
],
),
],
),
),
);
},
);
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Modal Bottom Sheet Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () => _showModalBottomSheet(context),
child: const Text('Show Modal Bottom Sheet'),
),
),
);
}
Explination
- This code will create a dialog pinned to the bottom of the screen
- The
ModalBottomSheet
contains a text message and two buttons “Confirm” and “Close”. When the buttons are pressed, the modal bottom sheet closes, but with confirm – you could execute some additional logic. isDismissible
– is the flag that makes the bottom sheet modal. You could pass true and it will be closable – by tapping on the gray area. Use cases for it may be – when the bottom sheet displays errors.
Similar example, but with centered on the screen modal component is the Dialog https://programtom.com/dev/2024/10/18/flutter-modal-dialog/