flutter:使用listview之二:下拉刷新(flutter 3.7.0)

一,dart代码:

1,list.dart

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:demolist/model/ListOne.dart';
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class ItemList extends StatefulWidget {
  @override
  _MyList  createState()=> _MyList();
}

//封装的动态页面类
class _MyList extends State<ItemList>{

  ScrollController _scrollController = ScrollController(); //listview 的控制器
  //存放数据
  List<ListOne> _listData=[];
  //当前第几页
  int _currentPage = 0;
  int _total = 1;

  //http方式获取数据
  Future<Null> getHttp() async{
    String url = 'http://api.lhdtest.com/item/list?page='+_currentPage.toString();
    print(url);
    try {
      var response = await Dio().get(url);
      //处理json到类中
      var resoMap=json.decode(response.toString());
      _total = resoMap['data']['total'];
      for (int i = 0; i < (resoMap['data']['list'].length); i++) {
        var itemOne = resoMap['data']['list'][i];
        ListOne goodsOne = new ListOne(itemOne['title'],itemOne['author'], itemOne['id']);
        _listData.add(goodsOne);
      }
      setState(() {
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getHttp();
  }

  //构造list的item
  Widget _buildRow(int index) {
    //非最后一行
    return Container(
      margin: EdgeInsets.all(0),
      color: Colors.white,
      child: Container(
          width:560.w,
          height:160.w,
          margin: EdgeInsets.fromLTRB(20.w, 20.w, 20.w, 0),
          //color: Colors.cyan,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(30.w)),
          color: Colors.grey.withAlpha(40),
        ),
          child:Row(
          children:[
                  _titleWrapper(context, _listData[index].title),
                  _authorWrapper(context, _listData[index].author),
          ]
      ),
      ),
    );
  }

  Widget _authorWrapper(BuildContext context, String text) {
    return Container(
      height: 160.w,
      width:150.w,
      margin: EdgeInsets.fromLTRB(0.w, 0, 0, 0),
      decoration: new BoxDecoration(
        //color: Colors.yellow,
      ),
      alignment: Alignment.centerLeft,
      child: Text(
        text,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: Theme.of(context).textTheme.headline6,
      ),
    );
  }

  Widget _titleWrapper(BuildContext context, String text) {
    return Container(
      height: 160.w,
      width:500.w,
      margin: EdgeInsets.fromLTRB(20.w, 0, 0, 0),
      decoration: new BoxDecoration(
        //color: Colors.red,
      ),
      alignment: Alignment.centerLeft,
      child: Text(
        text,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: Theme.of(context).textTheme.headline6,
      ),
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var content;
    if (_listData.length == 0) {
      content = new Center(
        // 可选参数 child:
        child: new CircularProgressIndicator(),
      );
    } else {
      content = _contentList();
    }

    //设置尺寸(填写设计中设备的屏幕尺寸)如果设计基于750dp * 1334dp的屏幕
    ScreenUtil.init(
        context,
        designSize: Size(750, 1334)
    );

    return Scaffold(
      appBar: AppBar(title: Text('小学三年级部编版'),),
      body: content,
    );
  }
  Widget _contentList() {
    return Stack(
      children: [
        new RefreshIndicator(
            onRefresh: _onRefresh,
            child: ListView.builder(
              itemCount: _listData.length,
              itemBuilder: (BuildContext context, int index) {
                return getItem(context,index);
              },
              controller: _scrollController,
            )),
      ],
    );
  }

  //下拉刷新执行
  Future<void> _onRefresh() async {
    print('执行刷新');
    this._listData.clear();
    _currentPage = 1;
    getHttp();
    await Future.delayed(Duration(milliseconds: 500), () {
      print('refresh');
    });
  }

  Widget getItem(BuildContext context,int index) {
    return new GestureDetector(
      child:_buildRow(index),
    );
  }
}

2,listone.dart

class ListOne {
  String title;
  String author;
  int id;

  ListOne(this.title,this.author, this.id) {}

  ListOne.fromJson(Map<String, dynamic>json)
      :title=json["title"],
        author = json["author"],
        id = json["id"];
}

3,接口返回的数据格式:

说明:刘宏缔的架构森林是一个专注架构的博客,

网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/06/04/flutter-shi-yong-listview-zhi-er-xia-la-shua-xin-flutter-3-7/

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,测试效果

三,查看flutter的版本:

liuhongdi@liuhongdideMBP ~ % flutter --version
Flutter 3.7.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision b06b8b2710 (2 weeks ago) • 2023-01-23 16:55:55 -0800
Engine • revision b24591ed32
Tools • Dart 2.19.0 • DevTools 2.20.1

 

posted @ 2023-02-09 16:30  刘宏缔的架构森林  阅读(487)  评论(0编辑  收藏  举报