如何为所有BLoC调用AlertDialog

时间:2019-07-11 12:50:08

标签: flutter bloc

我正在为自己的应用程序使用BLoC模式。我想调用AlertDialog并在一个位置显示所有BLoC的异常,但不将AlertDialog调用代码添加到所有页面。我可以使用SimpleBlocDelegate中的onError回调来调用AlertDialog并将其显示在当前活动页面上吗?我该怎么办。

main.dart的一部分

class SimpleBlocDelegate extends BlocDelegate {

      @override
      void onEvent(Bloc bloc, Object event) {
        super.onEvent(bloc, event);
        print("Event: $event");
      }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print("Transition : $transition");
  }

  @override
  void onError(Bloc bloc, Object error, StackTrace stacktrace) {

    super.onError(bloc, error, stacktrace);

!!!! Call here Alert dialog and show it on current active page 

    print("Error in bloc : $error");
  }
}


void main() {

  BlocSupervisor().delegate = SimpleBlocDelegate();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    runApp(new MyApp());
  });
}


class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      theme: ThemeData(
        cursorColor: Colors.grey[500],
      ),
      initialRoute: '/',
      routes: {
        '/':(BuildContext context) => LoginPage(),
        '/restore':(BuildContext context) => RestorePage(),
      },
      debugShowCheckedModeBanner: false,
    );
  }
}

我想我可以像这样调用show AlertDialog,但是我应该设置当前页面的上下文。是正确的方法,我应该从GlobalKey还是以任何其他方式获取当前上下文?

@override
  void onError(Bloc bloc, Object error, StackTrace stacktrace) {

    super.onError(bloc, error, stacktrace);
    print("Error in bloc : $error");

    WidgetsBinding.instance.addPostFrameCallback((_) => showDialog(
      context: ?????,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Login error"),
          content: new Text(error.toString()),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("Close"),
              onPressed: () {
                bloc.dispatch('');
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    ));
  }

感谢您的帮助。

0 个答案:

没有答案