如何在Flutter中根据文本使SnackBar宽度灵活?

3

Snackbar的宽度只能通过参数width进行设置,否则它将使用全屏宽度。

有没有办法让它变得灵活一些?

编辑:类似下面这样的效果。

enter image description here

enter image description here


使用 Toast 会更适合您。因为您分享的图片看起来像是 Toast 消息,而不是 Snackbar。 - srihari ayapilla
这是一个具有自定义颜色和宽度的 Snackbar。 - bounxye
有没有使用Snackbar和AutosizedText的解决方案?而不是使用Flutter Toast。 - undefined
3个回答

0
有一个非常有用的软件包可以使用——fluttertoast
只需编写以下内容-
Fluttertoast.showToast(
        msg: "This is Center Short Toast",
    );

您可以添加toastLength来使其变得短或长 -
Fluttertoast.showToast(
        msg: "This is Center Short Toast",
        toastLength: Toast.LENGTH_SHORT,
    );

希望这可以帮到您。请告诉我。

-1
这里的技巧是我使用了透明背景。您可以创建一个传递上下文和大小的方法。
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具有响应式宽度。 - bounxye
你喜欢只有文本占据空间,你也可以使用mediaQuery来传递宽度。你能否包含一张你正在尝试实现的图片? - Yeasin Sheikh

-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),
    );


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接