flutter dio网络请求和listview显示

import 'dart:convert';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:music/data/GetMomentList.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new Page();
  }
}

class Page extends State<HomePage> {
  //不知道什么类型就用var
  var _items = [];

  @override
  Widget build(BuildContext context) {
    return layout(context);
  }

  @override
  void initState() {
    super.initState();
    getMomentLists();
  }

  //获取动态列表接口
  getMomentLists() async {
    var apiUrl = "http://47.242.63.216:9527/v1/moment/getList";

    SharedPreferences prefs = await SharedPreferences.getInstance();
    var tokens = prefs.getString("token");

    //参数
    Map map = {};
    //动态ID,0就是最新的
    map["moment_id"] = 0;

    //网络请求添加token请求头
    Response result = await Dio().post(apiUrl,
        data: map, options: Options(headers: {"x-token": tokens}));
    log(result.toString());

    //json解析
    Map<String, dynamic> nickname = json.decode(result.toString());
    var httpRes = GetMomentList.fromJson(nickname);
    //如果成功就吐司
    if (httpRes.code == 200) {
      setState(() {
        //将list字段的内容赋值给全局变量_items
        _items = httpRes.data.list;
        log(_items.length.toString());
      });

    }
  }

  Widget layout(BuildContext context) {
    return new Scaffold(
      appBar: buildAppBar(context),
      body:
          //使用ListView.builder创建列表
      new ListView.builder(itemCount: _items.length, itemBuilder: itemView),
    );
  }

  //方法体
  Widget itemView(BuildContext context, int index) {
    List1 model = this._items[index];
    return new Container(
        color: Color.fromARGB(0x22, 0x49, 0xa9, 0x8d),
        child: new Padding(
            padding: const EdgeInsets.all(8.0),
            child: new Padding(
                padding: const EdgeInsets.all(8.0),
                child: new Column(
                  children: <Widget>[
                    new Row(
                      children: <Widget>[
                        new Text('${model.momentInfo.createTime}年${model.userInfo.userId}月',
                            style: new TextStyle(fontSize: 15.0)),
                        new Text('(${model.userInfo.userId})',
                            style: new TextStyle(fontSize: 15.0)),
                      ],
                    ),
                    new Center(
                      heightFactor: 6.0,
                      child: new Text("${model.userInfo.userId}",
                          style: new TextStyle(fontSize: 17.0)),
                    )
                  ],
                ))));
  }

  Widget buildAppBar(BuildContext context) {
    return new AppBar(title: const Text('历史今日'));
  }
}

另外一个事例

import 'dart:convert';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:music/Utils/StringUtil.dart';
import 'package:music/data/GetMomentList.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new Page();
  }
}

class Page extends State<DynamicRecommendNav> {
  //不知道什么类型就用var
  var _items = [];

  @override
  Widget build(BuildContext context) {
//通过下面这种方法解决多图片问题
    if (_items.length == 0) {
      return layout1(context);
    } else if (_items.length == 3) {
      return layout(context);
    } else {
      return layout(context);
    }
  }

  @override
  void initState() {
    super.initState();
    getMomentLists();
  }

  //获取动态列表接口
  getMomentLists() async {
    var apiUrl = "http://47.242.63.216:9527/v1/moment/getList";

    SharedPreferences prefs = await SharedPreferences.getInstance();
    var tokens = prefs.getString("token");

    //参数
    Map map = {};
    //动态ID,0就是最新的
    map["moment_id"] = 0;

    //网络请求添加token请求头
    Response result = await Dio().post(apiUrl,
        data: map, options: Options(headers: {"x-token": tokens}));
    log(result.toString());

    //json解析
    Map<String, dynamic> nickname = json.decode(result.toString());
    var httpRes = GetMomentList.fromJson(nickname);
    //如果成功就吐司
    if (httpRes.code == 200) {
      setState(() {
        //将list字段的内容赋值给全局变量_items
        _items = httpRes.data.list;
        log(_items.length.toString());
      });
    }
  }

  Widget layout(BuildContext context) {
    return new Scaffold(
      body: Container(
        //设置界面背景
        decoration: const BoxDecoration(
          color: Color(0xFF1F1F1F),
        ),
        //使用ListView.builder创建列表
        child:
        ListView.builder(itemCount: _items.length, itemBuilder: itemView),
      ),
    );
  }

  Widget layout1(BuildContext context) {
    return new Scaffold(
      body:
      //使用ListView.builder创建列表
      new ListView.builder(
          itemCount: _items.length, itemBuilder: itemView1),
    );
  }

  //发动态的文字
  Row dynamicTxtSection(String text) {
    return Row(
      children: [
        Container(
          margin: EdgeInsets.only(left: 16, bottom: 17),
          child: Text(
            text,
            style: TextStyle(color: Color(0xFFBBBBBB), fontSize: 16),
          ),
        )
      ],
    );
  }

  //地点行
  Widget placeSection(String area) {
    return Row(
      children: [
        GestureDetector(
            child: Container(
              margin: const EdgeInsets.only(left: 15.0),
              child: Text(
                area,
                style: TextStyle(color: Color(0xFF888888)),
              ),
            )),
      ],
    );
  }

  //互动行
  Widget interactiveSection() {
    return Container(
      margin: const EdgeInsets.only(top: 25.0, left: 15.0, bottom: 51.0),
      child: Row(
        children: [
          Container(
            width: 25.0,
            child: Image.asset(
              "assets/base_widgets/icon_dynamic_recom_like.png",
              fit: BoxFit.fitWidth,
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 6.0, right: 24.0),
            child: Text(
              "996",
              style: TextStyle(color: Color(0xFFBBBBBB)),
            ),
          ),
          Container(
            width: 25.0,
            child: Image.asset(
              "assets/base_widgets/icon_dynamic_recom_Comment.png",
              fit: BoxFit.fitWidth,
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 6.0, right: 24.0),
            child: Text(
              "65",
              style: TextStyle(color: Color(0xFFBBBBBB)),
            ),
          ),
          Container(
            width: 25.0,
            child: Image.asset(
              "assets/base_widgets/icon_dynamic_gift_box.png",
              fit: BoxFit.fitWidth,
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 6.0, right: 24.0),
            child: Text(
              "1066",
              style: TextStyle(color: Color(0xFFBBBBBB)),
            ),
          )
        ],
      ),
    );
  }

  //列表的名称
  List<String> SONGNAME = [
    '音乐1',
    '音乐2',
    '音乐3',
  ];

  //动态图片列表方法体
  Widget dynamicItem(String name) {
    return Column(
      mainAxisSize: MainAxisSize.max,
      children: [
        Container(
          width: 110,
          height: 110,
          decoration: BoxDecoration(
              color: Colors.grey[300],
              image: const DecorationImage(
                  image: NetworkImage(
                      "https://www.itying.com/images/flutter/3.png"),
                  fit: BoxFit.fill),
              borderRadius: BorderRadius.circular(10)),
          margin: const EdgeInsets.only(left: 15.0, bottom: 12.0),
        ),
      ],
    );
  }

  //动态列表第一排
  Widget dynamicListSection() {
    return SizedBox(
      height: 130,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: SONGNAME.map((city) => dynamicItem(city)).toList(),
      ),
    );
  }

  //动态列表第二排
  Widget dynamicListSection2() {
    return SizedBox(
      height: 130,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: SONGNAME.map((city) => dynamicItem(city)).toList(),
      ),
    );
  }

  //item方法体
  Widget itemView(BuildContext context, int index) {
    List1 model = this._items[index];
    return new Column(
      children: [
        Container(
          //用decoration的BoxDecoration设置圆角
          decoration: const BoxDecoration(
            //设置背景颜色
            color: Color(0xFF1F1F1F),
          ),
          //左图中的第二个红框部分
          //边距
          margin: const EdgeInsets.only(
            left: 15.0,
          ),
          //内边距
          padding: const EdgeInsets.only(bottom: 10.0), //这个是该容器进行设置边距
          //在这个容器里面放着一行控件
          child: Row(
            //行里的控件
            children: [
              //行的第一个元素控件即头像
              Container(
                width: 50,
                height: 50,
                margin: const EdgeInsets.only(right: 15.0),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: NetworkImage(model.userInfo.avatar),
                    fit: BoxFit.cover,
                  ),
                  borderRadius: BorderRadius.circular(50),
                ),
              ),
              //行的第二个元素,Expanded相当于设置宽度为0,倍数为1,后面的控件就去到最后面了
              Expanded(
                //Container和Expanded都是只是描述的限制,他们后面的元素都要加child:
                //该部分里面是用列排布的
                child: Column(
                  //设置子项左对齐
                  crossAxisAlignment: CrossAxisAlignment.start,
                  //Row和Column里面是一堆控件,要用children:[]
                  children: [
                    //该行的第一个元素是嵌套的控件,设置一个容器装载
                    Container(
                      margin: const EdgeInsets.only(),
                      //第一个元素当作是一个容器,然后设置边距
                      padding: const EdgeInsets.only(bottom: 8.0),
                      //底部添加8像素填充
                      //列上第一个元素
                      child: Text(
                        //第一个元素
                        '${model.userInfo.nickname}',
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Color(0xFFFFFFFF),
                            fontSize: 17.0),
                      ),
                    ),
                    //列上的第二个元素是用行来排列的
                    Row(
                      children: [
                        //每个元素一般都是要加上Container的,因为要设置距离
                        Container(
                          padding: const EdgeInsets.only(
                              left: 8.0, right: 8.0, top: 3.0, bottom: 3.0),
                          decoration: BoxDecoration(
                            borderRadius: const BorderRadius.only(
                                topLeft: Radius.circular(10.0),
                                topRight: Radius.circular(10.0),
                                bottomLeft: Radius.circular(10.0),
                                bottomRight: Radius.circular(10.0)),
                            color: const Color(0xFFBBA57A),
                            border: Border.all(
                                width: 1, color: const Color(0xFFBBA57A)),
                          ),
                          child: const Text(
                            //第二个元素
                            '認證歌手',
                            style: TextStyle(
                                color: Color(0xFF1F1F1F),
                                fontSize: 12,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.only(
                              top: 3.0, bottom: 3.0, left: 8.0, right: 8.0),
                          margin:
                          const EdgeInsets.only(left: 10.0, right: 10.0),
                          decoration: const BoxDecoration(
                              color: Color(0xFFBBBBBB),
                              borderRadius:
                              BorderRadius.all(Radius.circular(10.0))),
                          child: Row(
                            children: [
                              Image.asset(
                                'assets/base_widgets/icon_dynamic_recom_male.png',
                                width: 13,
                                fit: BoxFit.fitWidth,
                              ),
                              Container(
                                  margin: const EdgeInsets.only(left: 5.0),
                                  child: Text(StringUtils.getAge(
                                      model.userInfo.birthday)))
                            ],
                          ),
                        ),
                        Container(
                          child: Image.asset(
                            'assets/base_widgets/icon_dynamic_recom_grade.png',
                            width: 50,
                            fit: BoxFit.fitWidth,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              // 行的第三个元素
              Container(
                padding: const EdgeInsets.only(bottom: 8.0), //底部添加8像素填充
                child: Column(
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        // pullBlack();
                      },
                      child: Container(
                          width: 35.0,
                          child: Image.asset(
                            "assets/base_widgets/icon_grey_more.png",
                            fit: BoxFit.fitWidth,
                          )),
                    ),
                    //空白文字用来顶位置
                    Text(''),
                  ],
                ),
              ),
            ],
          ),
        ),
        dynamicTxtSection(model.momentInfo.text),
        dynamicListSection(),
        dynamicListSection2(),
        placeSection(model.userInfo.area),
        interactiveSection(),
      ],
    );
  }

  //方法体
  Widget itemView1(BuildContext context, int index) {
    List1 model = this._items[index];
    return new Container(
        color: Color.fromARGB(0x22, 0x49, 0xa9, 0x8d),
        child: new Padding(
            padding: const EdgeInsets.all(8.0),
            child: new Padding(
                padding: const EdgeInsets.all(8.0),
                child: new Column(
                  children: <Widget>[
                    new Row(
                      children: <Widget>[
                        new Text(
                            '${model.momentInfo.userId}年${model.userInfo.userId}月',
                            style: new TextStyle(fontSize: 15.0)),
                        new Text('(${model.userInfo.userId})',
                            style: new TextStyle(fontSize: 15.0)),
                      ],
                    ),
                    new Center(
                      heightFactor: 6.0,
                      child: new Text("${model.userInfo.userId}",
                          style: new TextStyle(fontSize: 17.0)),
                    )
                  ],
                ))));
  }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值