当我滚动到flutter中的列表底部时,列表中的分页不起作用

发布于 2025-02-13 21:01:52 字数 6612 浏览 0 评论 0原文

面临问题。当我使用controller.position.position.extentafter<当我到达列表的底部时,我开始撰写列表,以便显示10个元素; 30 我检查了我们走了多远,如果在最底部,我会更改isloadMorerunning的值,并显示circularprogressIndicator。我还将为每个调用显示+10 Elements 。我似乎做对了所有事情,但是分页对我不起作用,它显示了前10个元素,然后什么都没有通过,当我滚动到最底部时,新元素不会加载。有什么问题?

home

late ScrollController controller;
  bool isFirstLoadRunning = false;
  bool isLoadMoreRunning = false;
  bool hasNextStation = true;
  int limit = 10;

  void _firstLoadStations() async {
    final StationCubit stationCubit = BlocProvider.of<StationCubit>(context);

    setState(() {
      isFirstLoadRunning = true;
    });

    try {
      stationsList =
          await stationCubit.getAllPublicChargingStations(limit: limit);
    } catch (error) {
      print(error);
    }

    setState(() {
      isFirstLoadRunning = false;
    });
  }

  void _loadMoreStations() async {
    final StationCubit stationCubit = BlocProvider.of<StationCubit>(context);

    if (hasNextStation == true &&
        isFirstLoadRunning == false &&
        controller.position.extentAfter < 30) {
      setState(() {
        isLoadMoreRunning = true;
      });
      limit += 10;

      try {
        var fetchedStations =
            await stationCubit.getAllPublicChargingStations(limit: limit);

        if (fetchedStations.isNotEmpty) {
          setState(() {
            stationsList.addAll(fetchedStations);
          });
        } else {
          setState(() {
            hasNextStation = false;
          });
        }
      } catch (error) {
        print(error);
      }
      setState(() {
        isLoadMoreRunning = false;
      });
    }

    // _foundAddressesInStationList = stationsList;
  }

  @override
  void initState() {
    _firstLoadStations();
    controller = ScrollController()
      ..addListener(() {
        _loadMoreStations();
      });
    _foundAddresses = _allAddresses;
    _foundStation = _allStation;
    super.initState();
  }

  @override
  void dispose() {
    controller.removeListener(() {
      _loadMoreStations();
    });
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    final double paddingTop = MediaQuery.of(context).padding.top;
    final StationCubit stationCubit = BlocProvider.of<StationCubit>(context);

    return Container(
      width: size.width,
      height: size.height,
      child: _child(size, paddingTop, stationCubit),
    );
  }

  Widget _child(Size size, double paddingTop, StationCubit stationCubit) =>
      BlocBuilder<StationCubit, StationState>(
        builder: (context, state) => Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: Column(
            children: [
              const SizedBox(height: 17),
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      _addresses(size, stationCubit),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      );

  Widget _addresses(Size size, StationCubit stationCubit) => ConstrainedBox(
        constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height / 2,
        ),
        child: SizedBox(
          width: size.width,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(24),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
              child: Container(
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        isFirstLoadRunning
                            ? const CircularProgressIndicator(
                                color: Colors.white)
                            : const Text(
                                'Addresses',
                                style: constants.Styles.smallBookTextStyleWhite,
                              ),
                        const SizedBox(height: 25),
                        ListViewSearch(
                          stationList: stationsList,
                          controller: controller,
                        ),
                        const SizedBox(height: 20),
                        if (isLoadMoreRunning == true)
                          const Padding(
                            padding: EdgeInsets.only(top: 10, bottom: 40),
                            child: Center(
                              child: CircularProgressIndicator(),
                            ),
                          ),
                        if (hasNextStation == false)
                          Container(
                            padding: const EdgeInsets.only(top: 30, bottom: 40),
                            color: Colors.amber,
                            child: const Center(
                              child:
                                  Text('You have fetched all of the content'),
                            ),
                          ),
                      ],
                    ),
                  )),
            ),
          ),
        ),
      );
}

cubit

 Future<List<PublicChargingStationModel>> getAllPublicChargingStations(
      {required int limit}) async {

    var result =
        await StationRepository().getAllPublicChargingStations(limit: limit);

    return result;
  }

存储库

Future<List<PublicChargingStationModel>> getAllPublicChargingStations(
      {int? limit}) async {
    try {
      var apiKeyMap = await ApiKey.getCryptoApiKeyMap();
      apiKeyMap!.addAll({'limit': limit.toString()});

      final Uri url = Uri.parse(
        '${ApiConfig.schema}://${ApiConfig.domain}/${ApiConfig.uriPrefix}/stations',
      ).replace(queryParameters: apiKeyMap);


      final response = await http.get(url);
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body)['data'] as List;
        return data
            .map((json) => PublicChargingStationModel.fromJson(json))
            .toList();
      }

      return List<PublicChargingStationModel>.empty();
    } catch (_) {
      print(_);
      return List<PublicChargingStationModel>.empty();
    }
  }

Faced a problem. I started to paginate the list so that 10 elements are displayed, when I reach the bottom of the list using controller.position.extentAfter < 30 I check how far we have gone down and if at the very bottom I change the value of isLoadMoreRunning and show CircularProgressIndicator. I will also add +10 elements to the limit variable for each call to display. I seem to have done everything right, but pagination does not work for me, it shows the first 10 elements, and then nothing passes, new elements are not loaded when I scrolled to the very bottom. What could be the problem?

home

late ScrollController controller;
  bool isFirstLoadRunning = false;
  bool isLoadMoreRunning = false;
  bool hasNextStation = true;
  int limit = 10;

  void _firstLoadStations() async {
    final StationCubit stationCubit = BlocProvider.of<StationCubit>(context);

    setState(() {
      isFirstLoadRunning = true;
    });

    try {
      stationsList =
          await stationCubit.getAllPublicChargingStations(limit: limit);
    } catch (error) {
      print(error);
    }

    setState(() {
      isFirstLoadRunning = false;
    });
  }

  void _loadMoreStations() async {
    final StationCubit stationCubit = BlocProvider.of<StationCubit>(context);

    if (hasNextStation == true &&
        isFirstLoadRunning == false &&
        controller.position.extentAfter < 30) {
      setState(() {
        isLoadMoreRunning = true;
      });
      limit += 10;

      try {
        var fetchedStations =
            await stationCubit.getAllPublicChargingStations(limit: limit);

        if (fetchedStations.isNotEmpty) {
          setState(() {
            stationsList.addAll(fetchedStations);
          });
        } else {
          setState(() {
            hasNextStation = false;
          });
        }
      } catch (error) {
        print(error);
      }
      setState(() {
        isLoadMoreRunning = false;
      });
    }

    // _foundAddressesInStationList = stationsList;
  }

  @override
  void initState() {
    _firstLoadStations();
    controller = ScrollController()
      ..addListener(() {
        _loadMoreStations();
      });
    _foundAddresses = _allAddresses;
    _foundStation = _allStation;
    super.initState();
  }

  @override
  void dispose() {
    controller.removeListener(() {
      _loadMoreStations();
    });
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    final double paddingTop = MediaQuery.of(context).padding.top;
    final StationCubit stationCubit = BlocProvider.of<StationCubit>(context);

    return Container(
      width: size.width,
      height: size.height,
      child: _child(size, paddingTop, stationCubit),
    );
  }

  Widget _child(Size size, double paddingTop, StationCubit stationCubit) =>
      BlocBuilder<StationCubit, StationState>(
        builder: (context, state) => Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: Column(
            children: [
              const SizedBox(height: 17),
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      _addresses(size, stationCubit),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      );

  Widget _addresses(Size size, StationCubit stationCubit) => ConstrainedBox(
        constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height / 2,
        ),
        child: SizedBox(
          width: size.width,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(24),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
              child: Container(
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        isFirstLoadRunning
                            ? const CircularProgressIndicator(
                                color: Colors.white)
                            : const Text(
                                'Addresses',
                                style: constants.Styles.smallBookTextStyleWhite,
                              ),
                        const SizedBox(height: 25),
                        ListViewSearch(
                          stationList: stationsList,
                          controller: controller,
                        ),
                        const SizedBox(height: 20),
                        if (isLoadMoreRunning == true)
                          const Padding(
                            padding: EdgeInsets.only(top: 10, bottom: 40),
                            child: Center(
                              child: CircularProgressIndicator(),
                            ),
                          ),
                        if (hasNextStation == false)
                          Container(
                            padding: const EdgeInsets.only(top: 30, bottom: 40),
                            color: Colors.amber,
                            child: const Center(
                              child:
                                  Text('You have fetched all of the content'),
                            ),
                          ),
                      ],
                    ),
                  )),
            ),
          ),
        ),
      );
}

cubit

 Future<List<PublicChargingStationModel>> getAllPublicChargingStations(
      {required int limit}) async {

    var result =
        await StationRepository().getAllPublicChargingStations(limit: limit);

    return result;
  }

repository

Future<List<PublicChargingStationModel>> getAllPublicChargingStations(
      {int? limit}) async {
    try {
      var apiKeyMap = await ApiKey.getCryptoApiKeyMap();
      apiKeyMap!.addAll({'limit': limit.toString()});

      final Uri url = Uri.parse(
        '${ApiConfig.schema}://${ApiConfig.domain}/${ApiConfig.uriPrefix}/stations',
      ).replace(queryParameters: apiKeyMap);


      final response = await http.get(url);
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body)['data'] as List;
        return data
            .map((json) => PublicChargingStationModel.fromJson(json))
            .toList();
      }

      return List<PublicChargingStationModel>.empty();
    } catch (_) {
      print(_);
      return List<PublicChargingStationModel>.empty();
    }
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随波逐流 2025-02-20 21:01:52

您需要设置SinglechildScrollview参数控制器:控制器。

you need set SingleChildScrollView parameter controller: controller.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文