Flutter基础-051-SnackBar

325 阅读1分钟
构造方法
const SnackBar({
    Key key,
    @required this.content,   //现实的文字内容
    this.backgroundColor,// 背景色
    this.elevation,// 阴影长度
    this.shape,// 背景形状
    this.behavior,// fixed 固定在底部,弹出时会把页面上顶;floating   悬浮在页面上方
    this.action,// 添加操作
    this.duration = _snackBarDisplayDuration,// 持续时间,到时自动隐藏
    this.animation,
  })
示例

image.png

image.png

代码
class _MyHomePageState extends State<MyHomePage> {
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new Builder(builder: (BuildContext context) {
        return Center(
          child: GestureDetector(
            onTap: (){
              Scaffold.of(context).showSnackBar(SnackBar(
                content: Text("网络错误"),
                backgroundColor: Colors.orange[200],// 背景色
                elevation: 10,
                duration: Duration(seconds: 4),// 持续时间,到时自动隐藏
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),//背景形状
//                behavior: SnackBarBehavior.floating,// 悬浮
                behavior: SnackBarBehavior.fixed,// 固定在底部
                action: SnackBarAction(
                  label: "知道了",
                  onPressed: () {
                    Scaffold.of(context).hideCurrentSnackBar();// 隐藏
                  },
                ),
              ));
            },
            child: Text("show snackbar",style: TextStyle(fontSize: 29),),
          ),
        );
      }),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 无法弹出,必须在Builder中
//          Scaffold.of(context).showSnackBar(new SnackBar(
//            content: new Text("Snackbar"),
//            action: new SnackBarAction(
//              label: "撤回",
//              onPressed: () {},
//            ),
//          ));
        },
        child: Icon(Icons.airline_seat_recline_extra),
      ),
    );
  }
}