Display Bottom Sheet in Flutter

Display Bottom Sheet in Flutter

A bottom sheet is a surface that appears at the bottom of the screen. There are two types of bottom sheets:

  • Modal - disappears when the user clicks on the outside content.
  • Persistent - remains visible when the user clicks on the outside content.

Modal bottom sheet

The showModalBottomSheet() function can be used to display a modal bottom sheet.

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  void _showBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (builder) {
          return Container(
            height: 150,
            color: Colors.black12,
            child: const Center(
              child: Text('Hello world'),
            ),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Modal Bottom Sheet')),
        body: Center(
            child: ElevatedButton(
          onPressed: _showBottomSheet,
          child: const Text('Open'),
        )));
  }
}

Persistent bottom sheet

To display a persistent bottom sheet we need to have the current state of scaffold (ScaffoldState). So we create a final variable _scaffoldKey as a global key (GlobalKey). After that we assign variable to the key property of Scaffold class. Now we have access to the scaffold current state. Finally we use showBottomSheet() method to display a persistent bottom sheet.

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  void _showBottomSheet() {
    _scaffoldKey.currentState!.showBottomSheet((context) {
      return Container(
        height: 150,
        color: Colors.black12,
        child: const Center(
          child: Text('Hello world'),
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(title: const Text('Persistent Bottom Sheet')),
        body: Center(
            child: ElevatedButton(
          onPressed: _showBottomSheet,
          child: const Text('Open'),
        )));
  }
}

Leave a Comment

Cancel reply

Your email address will not be published.