Flutter Show Modal Bottom Sheet after build
Asked Answered
C

2

5

As the title says, I have a String parameter and when I load the Home Stateful Widget I would like to open this bottom sheet if the parameter is not null.

As I understood I can't call showModalBottomSheet() in the build function of the Home widget because it can't start building the bottom sheet while building the Home Widget, so, is there a way to call this immediately after the Home Widget is built?

Cupro answered 5/11, 2020 at 21:51 Comment(0)
I
16

One of the solutions might be using addPostFrameCallback function of the SchedulerBinding instance. This way you could call showModalBottomSheet after the Home widget is built.

import 'package:flutter/scheduler.dart';

...

  @override
  Widget build(BuildContext context) {
    SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
      showModalBottomSheet<void>(
        context: context,
        builder: (BuildContext context) {
          //Your builder code
        },
      );
    });

    //Return widgets tree for Home
  }
Immoral answered 5/11, 2020 at 22:16 Comment(1)
Thank you, that's exactly what I was looking forCupro
T
4

Here's one way:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      showModalBottomSheet(
        context: context, 
        builder: (BuildContext context) {
          return Container(
            child: Text('heyooo'),
          );
        }
      );
    });
    return Scaffold(
      appBar: AppBar(),
      body: Container(),
    );
  }
}
Tabular answered 5/11, 2020 at 22:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.