You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Widget叠加及将Widget置于容器顶角并部分超出显示?

Flutter实现Widget叠加并让组件超出容器顶角显示

要实现这种叠加效果,核心是用Stack组件完成层叠布局,配合Positioned定位超出容器的组件,同时关闭容器的裁剪行为,具体实现代码如下:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Container(
            width: 200,
            height: 200,
            color: Colors.grey[300],
            // 必须设置这个属性,否则超出容器的部分会被裁剪
            clipBehavior: Clip.none,
            child: Stack(
              children: [
                // 底层的主内容组件
                Center(
                  child: Text(
                    '主内容区域',
                    style: TextStyle(fontSize: 18),
                  ),
                ),
                // 顶角超出的悬浮组件
                Positioned(
                  // 负数值让组件部分超出容器左上角
                  top: -20,
                  left: -20,
                  child: Container(
                    width: 60,
                    height: 60,
                    decoration: BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.circular(30),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black26,
                          blurRadius: 4,
                          offset: Offset(2, 2),
                        )
                      ],
                    ),
                    child: Center(
                      child: Text(
                        '1',
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

关键说明:

  • Stack:负责将多个Widget按顺序层叠,后续的Widget会覆盖在前面的Widget之上
  • Positioned:通过top、left的负数值,让组件的一部分超出容器的顶角范围,数值大小可以根据需求调整
  • clipBehavior: Clip.none:容器默认会裁剪超出自身边界的子组件,设置该属性后,超出部分才能正常显示

内容的提问来源于stack exchange,提问作者sina .s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:50:26