Это хорошее решение для отображения SnackBar в случае ошибки с Flutter и MobX? - PullRequest
0 голосов
/ 23 января 2020

Вчера я потратил более десяти часов, пытаясь немного узнать MobX и применить простой SnackBar, если в API возникает ошибка. Мой вопрос заключается в том, может ли найденное мной решение считаться хорошим и подходящим или есть лучшее решение для реализации.

class _LoginPageState extends State<LoginPage> {
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  final _controller = Modular.get<LoginController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Observer(
        builder: (context) {
          if (_controller.token?.error != null) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              _scaffoldKey.currentState.showSnackBar(SnackBar(
                content: Text(_controller.token?.error),
                duration: Duration(seconds: 2),
              ));
            });
          }

          return Center(
            child: PrimaryButton(
              onPressed: () => _controller.authenticate(),
              text: 'Enviar',
              icon: Icons.send,
            ),
          );
        },
      ),
    );
  }
}

Если вам интересно, я использую flutter_modular, следовательно, Modular.get<>()

1 Ответ

0 голосов
/ 23 января 2020

Мне нравится этот подход, если вы убедитесь, что ваша закусочная НЕ охватывает содержимое страницы, поскольку вы знаете, что ошибки API могут быть сложными и хорошо документированы, поэтому вы можете прийти через ситуацию, когда закусочная будет охватывать ваш контент. Я обычно использую showDialog вместо этого, поскольку ошибки обычно не возникают. когда они это сделают, я выскажу sh всплывающее окно, отображающее и объясняющее ситуацию, используя детали ошибки.

Это моя настроенная версия всплывающих окон:

class ButtonsAndAction extends FlatButton{
  ///Providing a func is "optional", just pass null if you want the defualt action to pop the navigator.
  ButtonsAndAction(BuildContext context, String text, Function func ) : super(child: new Text(text, textDirection: Helper.textDirection(),style: TextStyle(color: ConstantValues.mainBackgroundColor)
  ,), onPressed: func == null ? () {Navigator.of(context).pop();} : func);
}

class Helper{
  static TextDirection textDirection() => AppConfig.rtl ? TextDirection.rtl : TextDirection.ltr;

  /// Used to push alerts of texts with a set of actions(buttons and actions) if wanted
  static Future pushDialog(BuildContext context, String title, String body, {List<ButtonsAndAction> actions, bool dismissable = true}) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return new WillPopScope(
        onWillPop: () async => dismissable,
        child:
        new AlertDialog(
          shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(ConstantValues.roundRadius)),
          side: BorderSide(color: ConstantValues.mainBackgroundColor, width: ConstantValues.roundBorderWidthForPopup)),
          title: new Container(child: new Text(title, textDirection: textDirection(), style: TextStyle(color: ConstantValues.mainBackgroundColor),), width: double.infinity,),
          content: new Container(child: SingleChildScrollView(child:
            new Text(body, textDirection: textDirection(), style: TextStyle(color: ConstantValues.mainBackgroundColor))), 
            width: double.infinity),
          actions: actions
        ));
      },
    );
  }
}

Удачи!

...