首页 > 其他分享 >flutter:使用listview之一(flutter 3.7.0)

flutter:使用listview之一(flutter 3.7.0)

时间:2023-02-03 18:14:37浏览次数:59  
标签:index return id 3.7 context child listview flutter

一,flutter代码

1,page/list.dart

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

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

//封装的动态页面类
class _MyList extends State<ItemList>{
  static const double ITEM_HEIGHT = 100;
  static const double TITLE_HEIGHT = 80;
  static const double MARGIN_SIZE = 10;
  ScrollController _scrollController = ScrollController(); //listview 的控制器
  //存放数据
  List<ListGoods> _listData=[];
  //当前第几页
  int _currentPage = 0;
  int _total = 1;

  //http方式获取数据
  Future<Null> getHttp() async{
    String url = 'http://api.lhdtest.com/goods/list?page='+_currentPage.toString();
    print(url);
    try {
      var response = await Dio().get(url);
      print(response);

      //处理json到类中
      var resoMap=json.decode(response.toString());
      _total = resoMap['data']['total'];
      print("total:"+_total.toString());
      for (int i = 0; i < (resoMap['data']['list'].length); i++) {
        print("i:"+i.toString());
        var itemOne = resoMap['data']['list'][i];
        print(itemOne);
        ListGoods goodsOne = new ListGoods(itemOne['name'],itemOne['desc'], 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.orange,
      child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children:[
            _imageWrapper("https://images.taboola.com.cn/taboola/image/fetch/f_jpg%2Cq_auto%2Ch_350%2Cw_420%2Cc_fill%2Cg_faces:auto%2Ce_sharpen/http%3A//cdn.taboola.com/libtrc/static/thumbnails/7dc5d37f2949e30163c870e0e5585592.jpg"),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _titleWrapper(context, _listData[index].name),
                  _descWrapper(context, _listData[index].desc),
                  _viewCountWrapper(_listData[index].id.toString(),_listData[index].id),
                ],
              ),
            )
          ]
      ),
    );
  }

  Widget _descWrapper(BuildContext context, String text) {
    return Container(
      height: 60,
      margin: EdgeInsets.fromLTRB(MARGIN_SIZE, 0, 0, 0),
      decoration: new BoxDecoration(
        color: Colors.yellow,
      ),
      child: Text(
        text,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: Theme.of(context).textTheme.headline6,
      ),
    );
  }

  Widget _titleWrapper(BuildContext context, String text) {
    return Container(
      height: 60,
      margin: EdgeInsets.fromLTRB(MARGIN_SIZE, 0, 0, 0),
      decoration: new BoxDecoration(
        color: Colors.red,
      ),
      child: Text(
        text,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: Theme.of(context).textTheme.headline6,
      ),
    );
  }

  Widget _viewCountWrapper(String text,int viewCount) {
    return Container(
      margin: EdgeInsets.fromLTRB(MARGIN_SIZE, 0, 0, 0),
      height: ITEM_HEIGHT - TITLE_HEIGHT,
      decoration: new BoxDecoration(
        color: Colors.blue,
      ),
      child: Row(children: [
        Icon(
          Icons.remove_red_eye_outlined,
          size: 14.0,
          color: Colors.grey,
        ),
        SizedBox(width: 5),
        Text(
          viewCount.toString(),
          style: TextStyle(color: Colors.grey, fontSize: 14.0),
        ),
      ]),
    );
  }

  Widget _imageWrapper(String imageUrl) {
    return SizedBox(
      width: 150,
      height: ITEM_HEIGHT,
      child: Image.network(imageUrl),
    );
  }

  @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();
    }

    return Scaffold(
      appBar: AppBar(title: Text('这是首页'),),
      body: content,
    );
  }
  Widget _contentList() {
    return  ListView.builder(
              itemCount: _listData.length,
              itemBuilder: (BuildContext context, int index) {
                return getItem(context,index);
              },
              controller: _scrollController,
    );
  }
  Widget getItem(BuildContext context,int index) {
    return new GestureDetector(
      child:_buildRow(index),
    );
  }
}

2,model/list_goods.dart

class ListGoods {
  String name;
  String desc;
  int id;

  ListGoods(this.name,this.desc, this.id) {}

  ListGoods.fromJson(Map<String, dynamic>json)
      :name=json["name"],
        desc = json["desc"],
        id = json["id"];

  Map<String, dynamic> toJson() {
    return {
      "name": name,
      "desc": desc,
      "id": id
    };
  }
}

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

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

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

说明:作者:刘宏缔 邮箱: [email protected]

二,测试效果

三,查看flutter的版本:

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

 

标签:index,return,id,3.7,context,child,listview,flutter
From: https://www.cnblogs.com/architectforest/p/17090118.html

相关文章

  • flutter —— RenderObject 的布局原理
    RenderObject的布局原理①relayoutBoundary重布局边界。该参数用于表示子节点布局变化是否影响父节点,如果为true,当子节点布局发生变化时父节点都会标记为需要重新布局,......
  • apache-zookeeper-3.7.1 安装部署
    apache-zookeeper-3.7.1安装部署下载地址:https://mirrors.bfsu.edu.cn/apache/zookeeper/apache-zookeeper-3.7.11.下载直接解压,进入../conf/目录下复制一份zoo_sample.......
  • Flutter Completer 的妙用
    适用场景:1.例如在app启动的时候,需要初始化数据(例如从服务端拉取数据),初始化的时间比较久,或者受限于网络,时间不可控,后面用户点击了某个操作,这个操作依赖于初始化,就需要等待初......
  • Flutter入门资料推荐
    前言群里很多入门小白不知道如何入门Flutter,水一篇文章简单介绍下本人学习过程中一些参考资料,方便Flutter小白少走弯路。非权威,推荐只针对本人经验来的说,大佬们不喜......
  • Linux下Python2.x升级Python3.7
    一、查看当前Python版本[root@localhost~]#python-VPython2.7.5二、下载新的python包并安装进入Python官网(https://www.python.org),选择需要的版本。此处我选择Py......
  • flutter:安装使用自定义的字体(flutter 3.7.0)
    一,在flutter项目中引入字体文件在项目中创建存放字体的文件夹fonts,并把要使用到的字体文件复制到此文件夹下:如图:说明:刘宏缔的架构森林是一个专注架构的博客,地址:htt......
  • ListView - 仿照IOS拉到上下底部仍可继续拉并自动回弹
    PART_ONLY自定义类继承​​ListView​​,覆写​​overScrollBy()​​publicclassCListViewextendsListView{privatestaticfinalintMAX_OVERSCROLLY_DISTANCE......
  • flutter:安装使用第三方库:以dio为例(flutter 3.7.0 / dio 4.0.6)
    一,dio库的地址:国外:https://pub.dev/packages/dio国内:https://pub.flutter-io.cn/packages/dio如图:可以看到最新版本是4.0.6说明:刘宏缔的架构森林是一个......
  • flutter:新创建一个项目(flutter 3.7.0)
    一,创建flutter项目启动androidstuido点击NewFlutterProject打开界面如图:此处:如果flutterSDK的目录没问题,点击Next按钮如图:此处设置Projectname(项目名称)......
  • Python3.7采用CMD自动安装Pygame1.9.4
    ​​Python全栈工程师核心面试300问深入解析(2020版)----全文预览​​​​​​Python3.7采用CMD自动安装Pygame1.9.4,一步即可最近正在学习python开发游戏,需要安装Pygam......