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

如何在Stack widget中添加PageView widget实现页面滑动切换

PageView 集成方案

你原来的Stack组件是单页的内容载体,只需要把它作为PageView的子项,每一页对应一个独立的Stack即可,Scaffold的body直接替换为PageView组件就行。

具体实现步骤

  • 先定义页面数据集合,存储每一页的背景图路径、名言文本,后续拓展内容只需要修改这个集合即可
  • 把PageView作为Scaffold的body属性值,遍历数据集合生成每一页的Stack组件

完整修改后代码

class OverviewScreen extends StatefulWidget {
  @override
  _OverviewScreenState createState() => _OverviewScreenState();
}

class _OverviewScreenState extends State<OverviewScreen> {
  // 定义每一页的内容数据,可自行添加更多条目
  final List<Map<String, String>> pageData = [
    {
      "image": "Image/soc1.jpg",
      "quote": "This is my text"
    },
    {
      "image": "Image/soc2.jpg",
      "quote": "Second quote here"
    },
    {
      "image": "Image/soc3.jpg",
      "quote": "Third quote here"
    }
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text(
            "Hu   R   Rehman",
            style: TextStyle(fontFamily: "MonteCarlo"),
          ),
          centerTitle: true,
          leading: Icon(Icons.menu),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.vertical(bottom: Radius.circular(16))
          ),
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        // 这里把原来的Stack替换成PageView
        body: PageView.builder(
          // 页面总数和数据长度一致
          itemCount: pageData.length,
          itemBuilder: (context, index) {
            // 每一页返回你原来的Stack结构,内容用当前索引对应的数据
            return Stack(
              children: <Widget>[
                Image(
                  image: AssetImage(pageData[index]["image"]!),
                  fit: BoxFit.cover,
                  width: double.infinity,
                  height: double.infinity,
                ),
                Align(
                    alignment: Alignment.center,
                    child: Text(
                        pageData[index]["quote"]!,
                        style: TextStyle(
                            fontSize: 30.0,
                            fontFamily: "MonteCarlo",
                            color: Colors.white,
                            fontWeight: FontWeight.w700
                        )
                    )
                )
              ],
            );
          },
        ),
      ),
    );
  }
}

可选拓展

你可以额外添加PageController绑定到PageView的controller属性,实现指定页面跳转、监听页面切换事件等功能。

内容的提问来源于stack exchange,提问作者Sultan ul Arefin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:18:02