【问题标题】:Common Snackbar does not show常见的 Snackbar 不显示
【发布时间】:2019-11-26 10:59:10
【问题描述】:

我已经为 SnackBar 创建了一个 Common 类,

class MySnackBar extends StatelessWidget {
  String message;
  int duration;
  BuildContext context;
  MySnackBar(BuildContext context,String message, int duration) {
    this.message = message;
    this.duration = duration;
    this.context = context;
  }

  @override
  Widget build(BuildContext context) {
    return _showSnackBar(this.context, message, duration);
  }

  Widget _showSnackBar(BuildContext context, String message, int duration) {
    Scaffold.of(context).showSnackBar(SnackBar(
      content: Text(message),
      duration: Duration(seconds: duration),
    ));
  }
}

我正在像这样从我的其他小部件调用这个类,

 MySnackBar(
  context,
  _postDetailsModel
    .language.postScreen.bookmarkOwnMessage,
     3);

但它既不显示小吃栏也不抛出错误。谁能告诉我我缺少什么或者有没有办法创建常见的小吃店类?

【问题讨论】:

    标签: flutter flutter-layout


    【解决方案1】:

    你可以使用flushbarhttps://pub.dev/packages/flushbar

    创建自定义FlushBar

    import 'package:flushbar/flushbar.dart';
    import 'package:flutter/material.dart';
    
    Flushbar customFlushBar(BuildContext context,String text){
      return Flushbar(
        flushbarPosition: FlushbarPosition.TOP,
        message: text,
        icon: Icon(
          Icons.info_outline,
          size: 28.0,
          color: Colors.blue[300],
        ),
        duration: Duration(seconds: 3),
        leftBarIndicatorColor: Colors.blue[300],
      )..show(context);
    }
    

    你可以这样调用:

    customFlushBar(context, 'Sign in failed');
    

    【讨论】:

    • 谢谢,但我正在寻找没有任何第三方库的解决方案。
    【解决方案2】:

    你应该直接使用这个:

    void showSnackBar(BuildContext context, String message, int duration) {
        Scaffold.of(context).showSnackBar(SnackBar(
          content: Text(message),
          duration: Duration(seconds: duration),
        ));
      }
    

    作为一种方法,而不是作为一个小部件。

    【讨论】:

    • 我已经尝试过了,它会抛出Scaffold.of() called with a context that does not contain a Scaffold.
    • 关于它的话题很多,例如参见this onethis one
    • 但是我每次都必须在通用小部件中传递一个 scafoldkey,对吗?那是一种扼杀目的。但就目前而言,我认为这是唯一的方法。
    • 或者如第一个链接中所述,您使用构建器来提供包含 Scaffold 的上下文,这取决于您希望如何使用您的小吃店。就个人而言,我改用 Flushbar 来避免那些脚手架关键问题。
    猜你喜欢
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2016-10-04
    • 2018-02-20
    • 2019-12-15
    • 2019-08-28
    • 1970-01-01
    相关资源
    最近更新 更多