Flutter: bloc, how to show an alert dialog

前端 未结 5 1722
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 19:01

I´m new in the bloc pattern and stream stuff. I want to show up an alert dialog when I press a button, but I can´t find a way to do it. Actually my code is:

Widg         


        
5条回答
  •  太阳男子
    2021-02-19 19:48

    You can use BlocListener for showing Dialogs, Snackbars or for navigating to a new page.

    With this approach you may want to refactor to rely on the bloc state rather than accessing the stream directly.

    return Scaffold(
      appBar: AppBar(
        title: Text("Title"),
      ),
      body: BlocProvider(
        create: () => YourBloc(),
        child: Stack([
          SnackbarManager(),
          YourScreen(),
        ]),
      ),
    );
    ...
    
    /// This is basically an empty UI widget that only
    /// manages the snackbar
    class SnackbarManager extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return BlocListener(
          listener: (context, state) {
            if (state.hasMyData) {
              Scaffold.of(context).showSnackBar(SnackBar(
                content:
                    Text("I got data"),
              ));
            }
          },
          child: Container(),
        );
      }
    }
    

提交回复
热议问题