Flutter: bloc, how to show an alert dialog

前端 未结 5 1702
佛祖请我去吃肉
佛祖请我去吃肉 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:41

    I know I'm late to the party, but maybe this will help someone. I'm currently learning about BLoC myself and ran into a similar problem.

    First of all, I want to recommend the flutter_bloc package from pub.dev. It contains Widgets that help you with this like BlocListener and BlocConsumer.

    If you want to go without it, you could try using a StatefulWidget and listen to it separately and use your logic to show the dialog. (also make sure your stream is broadcasting as in my example, so it can have multiple listeners)

    I've made an example which you could copy-past into dartpad.dev/flutter:

    import 'dart:async';
    import 'package:flutter/material.dart';
    
    final myStream = StreamController.broadcast();
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          theme: ThemeData.dark(),
          debugShowCheckedModeBanner: false,
          home: Scaffold(
            body: Center(
              child: MyWidget(),
            ),
          ),
        );
      }
    }
    
    class MyWidget extends StatefulWidget {
      @override
      _MyWidgetState createState() => _MyWidgetState();
    }
    
    class _MyWidgetState extends State {
    
      initState() {
        super.initState();
        myStream.stream.listen((show){
          if(show)
            showDialog(
            barrierDismissible: false,
            context: context,
            builder: (context) {
              return AlertDialog(
                title: Text('MyDialog'),
                actions: [
                  TextButton(
                    child: Text('Close'),
                    onPressed: (){
                      myStream.sink.add(false);
                  }),
                ]
              );
            }
          );
          if(!show) {
            Navigator.pop(context);
          }
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Center(child: ElevatedButton(
          child: Text('Show Alert'),
        onPressed: (){
          myStream.sink.add(true);
        }));
      }
    }
    

提交回复
热议问题