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

Flutter中实现点击按钮切换分页链接并加载新壁纸

实现分页加载壁纸的解决方案

关键修改点

  • 添加_currentPage变量跟踪当前页码,初始值设为1
  • 新增_isLoading变量防止重复触发加载请求
  • 修改top2Fetch方法支持动态传参,区分首次加载和加载更多逻辑
  • 加入加载更多按钮,点击后页码自增并触发新数据爬取
  • 优化数据更新逻辑,支持追加新数据或替换现有数据

修改后的完整代码

class Top2 extends StatefulWidget {
  const Top2({Key? key}) : super(key: key);

  @override
  State<Top2> createState() => _Top2State();
}

class _Top2State extends State<Top2> {
  List<Map<String, dynamic>> top2Wall = [];
  bool top2Loaded = false;
  int _currentPage = 1;
  bool _isLoading = false;

  void top2Fetch({bool isLoadMore = false}) async {
    if (_isLoading) return;
    
    setState(() {
      _isLoading = true;
      if (!isLoadMore) {
        top2Wall.clear();
        top2Loaded = false;
      }
    });

    final top2Scraper = WebScraper('https://mobile.alphacoders.com');

    if (await top2Scraper.loadWebPage('/by-category/3?page=$_currentPage')) {
      final newWallpapers = top2Scraper.getElement(
        'div.container-masonry > div.item > a > img.img-responsive',
        ['src', 'title']);

      setState(() {
        if (isLoadMore) {
          top2Wall.addAll(newWallpapers);
        } else {
          top2Wall = newWallpapers;
        }
        top2Loaded = true;
        _isLoading = false;
      });
    } else {
      setState(() {
        _isLoading = false;
        // 可在此添加加载失败的提示逻辑
      });
    }
  }

  @override
  void initState() {
    super.initState();
    top2Fetch(isLoadMore: false);
  }

  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;
    return Scaffold(
      body: top2Loaded
          ? Container(
              height: screenSize.height,
              width: double.infinity,
              child: SingleChildScrollView(
                physics: const BouncingScrollPhysics(),
                child: Column(
                  children: [
                    Wrap(
                      children: [
                        for (int i = 1; i < top2Wall.length; i++)
                          WallCard(src: top2Wall[i]['attributes']['src'])
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      child: _isLoading
                          ? const CircularProgressIndicator(color: Colors.cyanAccent)
                          : ElevatedButton(
                              onPressed: () {
                                setState(() {
                                  _currentPage++;
                                });
                                top2Fetch(isLoadMore: true);
                              },
                              child: const Text('加载下一页'),
                            ),
                    ),
                  ],
                ),
              ),
            )
          : const Center(
              child: CircularProgressIndicator(color: Colors.cyanAccent),
            ),
    );
  }
}

逻辑说明

  • 页码控制:通过_currentPage记录当前页码,点击按钮时用setState自增页码,同时调用top2Fetch获取对应页面的数据
  • 加载状态管理:_isLoading变量避免重复发起请求,加载过程中显示进度指示器,提升用户体验
  • 数据更新:用isLoadMore参数区分场景,首次加载直接替换数据,加载更多时追加新数据到现有列表
  • 界面更新:所有状态变更都通过setState触发,确保Flutter自动重新构建界面并展示最新内容

内容的提问来源于stack exchange,提问作者Cheems Monarch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:48:24