Flutter 全屏添加背景图片

1,024 阅读1分钟

app突然来个需求,页面的背景颜色太单调了,要加一个渐变的颜色,还得是全屏(包括appbar栏)的人嘛。 本以为直接加一个Container中加个渐变色就欧克了,然后appbar栏没有变。 后面就用图片来搞,才解决了,直接上代码。 1、app页码不展示appbar栏

@override
  Widget build(BuildContext context) { 
    return Scaffold(
      // 取消的appBar
      //   appBar: null, // 不写也可以,表示没有
         appBar: AppBar( 
           toolbarHeight: 0, // 设置 AppBar 高度
         ),
        
      backgroundColor: Colors.transparent, // 全局背景是透明的
      extendBodyBehindAppBar: true, // 内容延伸到 AppBar 后面
      body: Stack( //定位
        children: [
          // ✅ 背景图片填充
          Positioned.fill(
            child: Image.asset(
              'assets/images/xxxx.png', // 图片
              fit: BoxFit.cover,
            ),
          ), // 图片占满全屏 做被被进图
          SafeArea(child: buildContent(controller, context)), // 这个就是要放的全屏的代码
          Positioned( // 全屏定位的一个icon图标
            right: 3, 
            top: 0,
            bottom: 0, // ✅ 父Stack撑满
            child: Center(
              // ✅ Positioned内垂直居中
              child: GestureDetector(
                onTap: () {},
                child: Image.asset(
                  "assets/images/xxxxx.png",
                  width: 60,
                  height: 42,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

2、app页码展示appbar栏

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true, //这个很重要
      backgroundColor: Colors.transparent,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        centerTitle: true,
        elevation: 0,
        title: Text(
          '学习交流',
          style: TextStyle(color: Colors.black, fontSize: 16),
        ),
      ),
      body: Stack(
        children: [
          // ✅ 背景图填充
          Positioned.fill(
            child: Image.asset(
              'assets/images/xxxx.png',
              fit: BoxFit.cover,
            ),
          ),
          // ✅ 内容
          Scaffold(
            backgroundColor: Colors.transparent,
            body: SafeArea(
              child:  Container(
                chilr: //页面内容
              ),
            ),
          ),
        ],
      ),
    );
  } 

目前就想到这个方法解决这个问题,还有其他的办法欢迎大家在下面讨论