loadData.dart 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import 'package:flutter/material.dart';
  2. class LoadDataDemo extends StatelessWidget {
  3. const LoadDataDemo({Key? key}) : super(key: key);
  4. @override
  5. Widget build(BuildContext context) {
  6. return Scaffold(
  7. appBar: AppBar(
  8. title: Text("获取数据"),
  9. centerTitle: true,
  10. ),
  11. body: RefreshPage());
  12. }
  13. }
  14. class RefreshPage extends StatefulWidget {
  15. RefreshPage({Key? key}) : super(key: key);
  16. @override
  17. _RefreshPageState createState() => _RefreshPageState();
  18. }
  19. class _RefreshPageState extends State<RefreshPage> {
  20. List<String> data = <String>[];
  21. late ScrollController controller;
  22. bool ifLoading = false;
  23. @override
  24. void initState() {
  25. super.initState();
  26. controller = ScrollController();
  27. List.generate(30, (i) => data.add("item ${i + 1}"));
  28. }
  29. @override
  30. Widget build(BuildContext context) {
  31. return Stack(children: [
  32. RefreshIndicator(
  33. onRefresh: () {
  34. return Future.delayed(Duration(seconds: 1), () {
  35. data = <String>[];
  36. List.generate(30, (i) => data.add("item ${i + 1}"));
  37. setState(() {
  38. data = data;
  39. });
  40. });
  41. },
  42. child: NotificationListener<ScrollNotification>(
  43. onNotification: (scroll) {
  44. if (!ifLoading &&
  45. scroll.metrics.maxScrollExtent <= controller.offset + 200) {
  46. setState(() {
  47. ifLoading = true;
  48. });
  49. List.generate(30, (i) {
  50. data.add("item ${data.length + 1}");
  51. });
  52. // setState(() {
  53. // data = data;
  54. // ifLoading = false;
  55. // });
  56. Future.delayed(Duration(seconds: 2), () {
  57. setState(() {
  58. data = data;
  59. ifLoading = false;
  60. });
  61. });
  62. }
  63. return true;
  64. },
  65. child: ListView.builder(
  66. controller: controller,
  67. shrinkWrap: true,
  68. itemCount: data.length,
  69. itemBuilder: (context, index) {
  70. return Container(
  71. height: 80,
  72. child: Text(data[index]),
  73. );
  74. },
  75. )),
  76. ),
  77. ifLoading
  78. ? Center(
  79. child: CircularProgressIndicator(),
  80. )
  81. : Container()
  82. ]);
  83. }
  84. }