Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter:How to show ModalBottomSheet at startup without any button click, I want to show it as the first screen of my App

Tags:

flutter

guide me where I have to put the initState() etc or any other solution? I want to display this modal sheet as my app launches the first screen it will. How can I achieve it in the flutter.

like image 335
Aansa Kanwal Avatar asked Oct 28 '25 08:10

Aansa Kanwal


1 Answers

You can copy paste run full code below
You can in initState use addPostFrameCallback call showModalBottomSheet
code snippet

class _MyStatelessWidgetState extends State<MyStatelessWidget> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      show(context);
    });
  }

  ...
  void show(BuildContext context) {
    showModalBottomSheet<void>(

working demo

enter image description here

full code

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: MyStatelessWidget(),
      ),
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatefulWidget {
  MyStatelessWidget({Key key}) : super(key: key);

  @override
  _MyStatelessWidgetState createState() => _MyStatelessWidgetState();
}

class _MyStatelessWidgetState extends State<MyStatelessWidget> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      show(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        child: const Text('showModalBottomSheet'),
        onPressed: () {
          show(context);
        },
      ),
    );
  }

  void show(BuildContext context) {
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 200,
          color: Colors.amber,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                const Text('Modal BottomSheet'),
                ElevatedButton(
                  child: const Text('Close BottomSheet'),
                  onPressed: () => Navigator.pop(context),
                )
              ],
            ),
          ),
        );
      },
    );
  }
}
like image 153
chunhunghan Avatar answered Oct 29 '25 22:10

chunhunghan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!