【问题标题】:How to make SnackBar width flexible based on text in flutter?如何根据 flutter 中的文本使 SnackBar 宽度灵活?
【发布时间】:2023-01-04 15:45:26
【问题描述】:

Snackbarwidth只能用参数width设置,否则使用全屏宽度。

有什么办法可以让它变得灵活吗?

编辑:像下面这样的东西。

【问题讨论】:

  • 改用吐司应该更适合你。由于您分享的图像看起来像吐司消息而不是小吃店。
  • 这是一个具有自定义颜色和宽度的小吃店。

标签: flutter flutter-layout snackbar


【解决方案1】:

您可以使用一个非常有用的包 - fluttertoast

简单地写 -

Fluttertoast.showToast(
        msg: "This is Center Short Toast",
    );

您可以添加 toastLength 使其变短或变长 -

Fluttertoast.showToast(
        msg: "This is Center Short Toast",
        toastLength: Toast.LENGTH_SHORT,
    );

希望这可以帮助。让我知道。

【讨论】:

    【解决方案2】:

    其他解决方案是使用oktoast,我们可以用位置参数改变位置

    showToast(
          "$_counter",
          duration: Duration(seconds: 2),
          position: ToastPosition.bottom,
          backgroundColor: Colors.black.withOpacity(0.8),
          radius: 13.0,
          textStyle: TextStyle(fontSize: 18.0),
        );
    
    

    【讨论】:

      【解决方案3】:

      诀窍是在这里我使用透明背景。您可以创建一个传递上下文和大小的方法。

      showMySnackBar({
        required BuildContext context,
        required double width,
        double? height,
      }) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            padding: EdgeInsets.zero,
            content: Column(
              mainAxisSize: MainAxisSize.min, // needed for flexible height
              children: [
                Container(
                  alignment: Alignment.center,
                  width: width,
                  height: height,
                  color: Colors.green,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text("MY snack"),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      }
      

      并使用

       showMySnackBar(context: context, width: 400);
      

      【讨论】:

      • 我不想发送硬编码值 400,我希望 Snackbar 具有响应宽度。
      • 你喜欢只有文本占用空间,你也可以使用 mediaQuery 来传递宽度?你能包括一张你试图存档的图像吗?
      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 2013-10-01
      • 2011-10-08
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多