Open In App

Flutter – BottomSheet Class

Last Updated : 21 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Bottom Sheet is one of the popular ways to show various options on the screen. This helps the user to switch to a new screen. You will see this bottom sheet in most of the app to add data or add some information such as address or ticket number. In this article, we are going to see how to implement the Bottom Sheet in our Flutter App.

Constructor of BottomSheet Class:

BottomSheet({Key key,
AnimationController animationController,
bool enableDrag: true,
BottomSheetDragStartHandler onDragStart,
BottomSheetDragEndHandler onDragEnd,
Color backgroundColor,
double elevation,
ShapeBorder shape,
Clip clipBehavior,
@required
VoidCallback onClosing,
@required 
WidgetBuilder builder})

Properties of BottomSheet Class:

  • backgroundColor: It is used to give background color to the bottom sheet.
  • elevation: It is used to give elevation to our bottom sheet.
  • builder: It provides a builder for the contents of the sheet.
  • clipBehaviour: It is used to clip the content of the sheet as specified.
  • enableDrag: If true, the bottom sheet can be dragged up and down and dismissed by swiping downwards.
  • hashCode: It represents the hash code of the object.
  • key: It is used to handle how one widget replaces another widget in the tree. 
  • onClosing: Used to assign action while the bottom sheet is closing.
  • onDragEnd: It is called when the user stops dragging the bottom sheet.
  • onDragStart: It is called when the user starts dragging the bottom sheet.
  • runTimeType: A representation of the runtime type of the object.
  • shape: It defines the shape of the bottom sheet.

Now let’s look into the implementation of the Bottom sheet. To Implement the Bottom Sheet in Flutter you have to follow the following steps:

Step 1: Navigate to main.dart() file and return Material App()

First, we have declared MyApp() in runApp in main function. Then we created StatefullWidget for MyApp in which we have returned MaterialApp(). In this MaterialApp() we have given the title of our App and then declared the theme of our App as Dark Theme. Then we have given our first screen or slider app in home: HomePage()

Dart




import 'package:flutter/material.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      //First Screen of our App
      home: HomePage(),
    );
  }
}


Create a StatefulWidget():

Create a StatefulWidget that provides a base structure to the application using the below code. In this code firstly we have created StatefulWidget for HomePage(). And in this HomePage() we have returned Scaffold() Widget.

Dart




class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
 
  @override
  // ignore: library_private_types_in_public_api
  _HomePageState createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return const Scaffold();
  }
}


Step 2: Build the Bottom Sheet

In this Scaffold Widget, we have given appbar in which we have given the title of an Appbar. After that in the body, we have declared a Container() which is wrapped with Center Widget and given a sample text as “Hello”.

Dart




class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
 
  @override
  // ignore: library_private_types_in_public_api
  _HomePageState createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //Appbar along with Title
      appBar: AppBar(
        title: const Text("Bottom Sheet"),
      ),
      body:Center(
         
        //Sample Text Written in Center of Screen
        // ignore: avoid_unnecessary_containers
        child: Container(
          child: const Text("Hello"),
        ),
      ),
    );
  }
}


Step 3: Create and add a FloatingAction Button

Now create a Floating Action Button, and then we have assigned floatingactionButton and given addition icon on this button. And in the on Pressed method, we have declared showModalBottomSheet(). In then, we have given Container widget in it which is wrapped in SingleChildScrollView() widget. Which is used to scroll the content in the bottom sheet. Again we have declared a Container() for the bottom sheet in which we have given border-radius to the top Right and top Left corner to make this Container circular.

Dart




//Floating Action Button
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add, color: Colors.white),
        onPressed: () {
          showModalBottomSheet(
              context: context,
              builder: (context) {
                //Scrolling given for content in Container()
                return SingleChildScrollView(
                    child: Container(
                        padding: EdgeInsets.only(
                            bottom: MediaQuery.of(context).viewInsets.bottom),
                        child: Container(
                          padding: const EdgeInsets.all(20),
                          decoration: const BoxDecoration(
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(20),
                              topLeft: Radius.circular(20),
                            ),
                          ),
                        )));
              });
        },
      ),


Step 4: Create Column to display content

In this Container() we have declared Column() widget in which we have given its children’s.First we added text heading in the Container(). And after that we added TextField(). In this TextField() we have given InputDecoration() which is used to declare the hint text. Then we added border as OutLineInputBorder() which is used to to give border side color. Also we can make TextField circular by adding border radius in OutlineInputBorder(). After we have given a RaisedButton() in which we have given text written on the button and color of the button.

Dart




//Create a Column to display it's content
                   padding: const EdgeInsets.all(20),
                   decoration: const BoxDecoration(
                     borderRadius: BorderRadius.only(
                       topRight: Radius.circular(20),
                       topLeft: Radius.circular(20),
                     ),
                   ),
                   //Create a Column to display it's content
                   child: Column(
                     children: [
                       const Text(
                         "Add Data",
                         style: TextStyle(
                             fontWeight: FontWeight.w600,
                             color: Colors.green,
                             fontSize: 20),
                       ),
                       const SizedBox(height: 10.0),
                       // TextField for giving some Input
                       const TextField(
                         decoration: InputDecoration(
                           border: OutlineInputBorder(
                             borderSide: BorderSide(color: Colors.green),
                           ),
                           hintText: "Add Item",
                           hintStyle: TextStyle(color: Colors.grey),
                         ),
                       ),
                       const SizedBox(height: 10),
 
                       //Button for adding items
                       ElevatedButton(
                         onPressed: null,
                         style: ButtonStyle(
                             backgroundColor:
                                 MaterialStateProperty.all(Colors.red),
                             textStyle: MaterialStateProperty.all(
                                 const TextStyle(fontSize: 30))),
                         child: const Text("Add"),
                       )
                       // RaisedButton is deprecated
                       // Instead Use ElevatedButton
 
                       // RaisedButton(
                       //   color: Colors.grey,
                       //   onPressed: null,
                       //   child: Text(
                       //     "ADD",
                       //     style: TextStyle(color: Colors.white),
                       //   ),
                       // )
                     ],
                   ),
                 ),


Full Code

Dart




import 'package:flutter/material.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      //First Screen of our App
      home: const HomePage(),
    );
  }
}
 
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
 
  @override
  // ignore: library_private_types_in_public_api
  _HomePageState createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //Appbar along with Title
      appBar: AppBar(
        title: const Text("Bottom Sheet"),
      ),
      body: Center(
        //Sample Text Written in Center of Screen
        // ignore: avoid_unnecessary_containers
        child: Container(
          child: const Text("Hello"),
        ),
      ),
 
//Floating Action Button
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add, color: Colors.white),
        onPressed: () {
          showModalBottomSheet(
              context: context,
              builder: (context) {
                //Scrolling given for content in Container()
                return SingleChildScrollView(
                  child: Container(
                    padding: EdgeInsets.only(
                        bottom: MediaQuery.of(context).viewInsets.bottom),
                    child: Container(
                      //Create a Column to display it's content
                      padding: const EdgeInsets.all(20),
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.only(
                          topRight: Radius.circular(20),
                          topLeft: Radius.circular(20),
                        ),
                      ),
                      //Create a Column to display it's content
                      child: Column(
                        children: [
                          const Text(
                            "Add Data",
                            style: TextStyle(
                                fontWeight: FontWeight.w600,
                                color: Colors.green,
                                fontSize: 20),
                          ),
                          const SizedBox(height: 10.0),
                          // TextField for giving some Input
                          const TextField(
                            decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.green),
                              ),
                              hintText: "Add Item",
                              hintStyle: TextStyle(color: Colors.grey),
                            ),
                          ),
                          const SizedBox(height: 10),
 
                          //Button for adding items
                          ElevatedButton(
                            onPressed: null,
                            style: ButtonStyle(
                                backgroundColor:
                                    MaterialStateProperty.all(Colors.red),
                                textStyle: MaterialStateProperty.all(
                                    const TextStyle(fontSize: 30))),
                            child: const Text("Add"),
                          )
                          // RaisedButton is deprecated
                          // Instead Use ElevatedButton
 
                          // RaisedButton(
                          //   color: Colors.grey,
                          //   onPressed: null,
                          //   child: Text(
                          //     "ADD",
                          //     style: TextStyle(color: Colors.white),
                          //   ),
                          // )
                        ],
                      ),
                    ),
                  ),
                );
              });
        },
      ),
    );
  }
}


Output:



Previous Article
Next Article

Similar Reads

Bottomsheet in Flutter
We can create bottomsheet in flutter. Basically, we have two types of bottomsheets in material design: Persistent and Modal. Bottomsheets are used when we want to perform actions. There are basically two types of Bottomsheets: Persistent and Modal. Persistent bottomsheet do not hide the screen content and focus on both sides. But Modal bottomsheet
3 min read
Flutter - Creating Bottomsheet GetX Library
Bottomsheets are the sheets displayed at the bottom to show any content which we want to display. Normally, when we create bottomsheet the syntax for creating is long, and it also uses context. To avoid this, we can create bottomsheet with simple code with the help of GetX library. We can create using syntax Get.bottomsheet() in Stateless widget al
3 min read
Is Flutter Worth Learning? Top 7 Reasons to Learn Flutter
In today's era, the usage of smartphones has increased exponentially and so has the use of mobile applications and websites. Meanwhile, considering future career prospects, learning web development and mobile app development is strongly recommended for all individuals. And when we come to mobile app development, there are two most-popular open-sour
5 min read
Flutter - Sharing Data Among Flutter Pages
In this article, we are going to find the solution for the problem statement "Import/send data from one page to another in flutter". Before going into the topic, there are some pre-requisites. Pre-requisites:Basics of dart programming language.Setting up Flutter in VS code or Setting up Flutter in Android Studio.Creating first flutter app | Hello W
4 min read
Flutter Quill - Rich Text Editor in Flutter Application
This post will explain how to integrate a rich text editor into your Flutter application so that it may enable rich text editing. There are many more things we can do with Flutter Quill, but they can get a little involved. The example below is a pretty basic demonstration of what we mean. Let's first discuss what flutter quill is and why we need it
5 min read
Flutter - Animated AlertDialog in Flutter
Animating an AlertDialog in Flutter involves using the Flutter animations framework to create custom animations for showing and hiding the dialogue. In this article, we are going to add an animation to an AlertDialog. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.
4 min read
Flutter - Different Types of Loading using Flutter EasyLoading
Flutter applications involve incorporating loading indicators to provide users with feedback during background operations. Flutter has a package for simplifying the process named flutter_easyloading package. This package easiest way to integrate loading indicators with various styles. In this article, we will implement different types of loading in
5 min read
Flutter - ColoredBox Class Widget
A Colored Box is a container that fills it with color according to its child or A widget that paints its area with a specified Color and then draws its child on top of that color. A sample image is given below to get an idea about what we are going to do in this article. [caption width="800"] [/caption]How to use it? You can simple use this widget
3 min read
MaterialApp class in Flutter
MaterialApp Class: MaterialApp is a predefined class or widget in a flutter. It is likely the main or core component of a flutter app. The MaterialApp widget provides a wrapper around other Material Widgets. We can access all the other components and widgets provided by Flutter SDK. Text widget, DropdownButton widget, AppBar widget, Scaffold widget
7 min read
Scaffold class in Flutter with Examples
Scaffold is a class in flutter which provides many widgets or we can say APIs like Drawer, Snack-Bar, Bottom-Navigation-Bar, Floating-Action-Button, App-Bar, etc. Scaffold will expand or occupy the whole device screen. It will occupy the available space. Scaffold will provide a framework to implement the basic material design layout of the applicat
6 min read
Article Tags :