Why is 2 widgets need for Show modal Bottom sheet in flutter?

Issue

Why is 2 stateless widgets needed to create an modal bottom sheet in flutter? Why can’t we use one???
Why do we have to have a main widget with scaffold and then enter another widget in it? When I try it with one Stateless widget class, it doesn’t work. Why?

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  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: const MyStatelessWidget(),
      ),
    );
  }
}

class MyStatelessWidget extends StatelessWidget {
  const MyStatelessWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        child: const Text('showModalBottomSheet'),
        onPressed: () {
          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),
                      )
                    ],
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

Solution

It’s all about the BuildContext property of the build method.
MaterialApp and Scaffold introduces Material widgets to the Widget Tree that are necessaries to showModalBottomSheet method to work properly. So, if you declare your showModalBottomSheet together with the MaterialApp and Scaffold in the same StatelessWidget, the context is the same, and this context doesn’t have still the MaterialApp and Scaffold components, they are going to be introduced in the widget tree when build method finishes.

Instead of that, if you declare your component in a separated widget, the BuildContext context property of the build method of your new widget does have data about the material widgets previously created, so that’s why it works as expected.

Answered By – Yansaro Rodriguez Paez

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *