关于flutter:Flutter-学习第二课Dio网络请求简单用法和数据适配

6次阅读

共计 4399 个字符,预计需要花费 11 分钟才能阅读完成。

主页 main.dart

import 'package:flutter/material.dart';
import 'package:flutter_first/pages/good_list_page.dart';

void main() {runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      title: "Dio 申请",
      home: Scaffold(
        appBar: AppBar(title: Text('Dio 申请'),
        ),
        body: GoodListPage(),),
    );
  }
}

二:数据模型层
good_list_model.dart

// 商品列表数据模型

class GoodListModel {
  // 状态码
  String? code;

  // 状态信息
  String? message;

// 商品列表数据
  late List<GoodModel> data;

  // 构造方法,初始化时传入空数组 [] 即可

  GoodListModel({required this.data,this.code, this.message});

  // 通过传入 json 数据转换成数据模型

  GoodListModel.fromJson(Map<String, dynamic> json) {code = json['code'];
    message = json['message'];
    if (json['data'] != null) {data = <GoodModel>[];
      // 循环迭代 Json 数据冰将其每一项数据转成 GoodModel
      json['data'].forEach((v) {data.add(GoodModel.fromJson(v));
      });
    }
  }

  // 将数据模型转成 Json
  Map<String, dynamic> toJson() {final Map<String, dynamic> data = Map<String, dynamic>();
    data['code'] = this.code;
    data['message'] = this.message;
    if (this.data != null) {data['data'] = this.data.map((v) => v.toJson()).toList();}
    return data;
  }
}

class GoodModel {
  // 商品图片
  String? image;

  // 原价
  int? oriPrice;

// 现有价格
  int? presentPrice;

  // 商品名称
  String? name;

// 商品 Id
  String? goodsId;

// 构造方法
  GoodModel({this.image, this.oriPrice, this.presentPrice, this.name, this.goodsId});

// 通过传入的 Json 数据转换成数据模型
  GoodModel.fromJson(Map<String, dynamic> json) {image = json['image'];
    oriPrice = json['oriPrice'];
    presentPrice = json['presentPrice'];
    name = json['name'];
    goodsId = json['goodsId'];
  }

// 将数据模型转成 Json
  Map<String, dynamic> toJson() {final Map<String, dynamic> data = new Map<String, dynamic>();
    data['image'] = this.image;
    data['oriPrice'] = this.oriPrice;
    data['presentPrice'] = this.presentPrice;
    data['name'] = this.name;
    data['goodsId'] = this.goodsId;
    return data;
  }
}

三:数据申请 Dio
http_service.dart

//Dio 申请办法封装
import 'dart:io';

import 'package:dio/dio.dart';

Future request(url, {formData}) async {
  try {
    Response response;
    Dio dio = Dio();
    dio.options.contentType =
        ContentType.parse('application/x-www-form-urlencoded') as String?;
    // 发动 POST 申请,传入 url 及表单参数
    response = await dio.post(url, data: formData);
    // 胜利返回
    if (response.statusCode == 200) {return response;} else {throw Exception('后端接口异样,请查看测试代码和服务器运行状况....');
    }
  } catch (e) {return print('error:::${e}');
  }
}

四:数据申请加载页
good_list_page.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_first/model/good_list_model.dart';
import 'package:flutter_first/service/http_service.dart';

class GoodListPage extends StatefulWidget {_GoodListPageState createState() => _GoodListPageState();}

class _GoodListPageState extends State<GoodListPage> {
  // 初始化数据模型
  GoodListModel goodsList = GoodListModel(data: []);

  // 滚动管制
  var scrollController = ScrollController();

  @override
  void initState() {super.initState();
    // 获取商品的数据
    getGoods();}

  // 获取商品的数据
  void getGoods() async {
    // 申请 url
    var url = 'http://127.0.0.1:3000/getDioData';
    // 申请参数
    var formData = {'shopId', '001'};
    // 调用申请办法传入 url 和表单数据
    await request(url, formData: formData).then((value) {
      // 返回数据进行 Json 解码
      var data = json.decode(value.toString());
      // 打印数据
      print('商品列表数据 Json 格局:::' + data.toString());
      // 设置状态刷新
      setState(() {
        // 将返回的 Json 数据转换成 Model
        goodsList = GoodListModel.fromJson(data);
      });
    });
  }

  // 商品列表项
  Widget _ListWidget(List newList, int index) {
    return Container(padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
      // 程度方向布局
      child: Row(
        children: <Widget>[
          // 返回商品图片
          _goodsImage(newList, index),
          SizedBox(width: 10,),
          // 右侧应用垂直布局
          Column(
            children: <Widget>[_goodsName(newList, index),
              _goodsPrice(newList, index)
            ],
          )
        ],
      ),
    );
  }

  // 商品图片
  Widget _goodsImage(List newList, int index) {
    return Container(
      width: 150,
      height: 150,
      child: Image.network(newList[index].image,
        fit: BoxFit.fitWidth,
      ),
    );
  }

  // 商品名称
  Widget _goodsName(List newList, int index) {
    return Container(padding: EdgeInsets.all(5.0),
      width: 200,
      child: Text(newList[index].name,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  // 商品价格
  Widget _goodsPrice(List newList, int index) {
    return Container(margin: EdgeInsets.only(top: 20.0),
      width: 200,
      child: Row(
        children: <Widget>[
          Text('价格:¥${newList[index].presentPrice}',
            style: TextStyle(color: Colors.red),
          ),
          Text('价格:¥${newList[index].oriPrice}')
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 通过商品列表数组长度判断是否有数据
    if (goodsList.data.length > 0) {
      return ListView.builder(
        // 滚动器
        controller: scrollController,
        // 列表长度
        itemCount: goodsList.data.length,
        // 列表项结构器
        itemBuilder: (context, index) {
          // 列表项,传入列表项数据及索引
          return _ListWidget(goodsList.data, index);
        },
      );
    }
    // 商品列表没有数据时候返回空容器
    return Container();}
}

http://127.0.0.1:3000/getDioData 获取不到数据
我这个数据申请接口有问题,我只是练习一下数据申请怎么解决的流程

Dio 的 github 地址:https://github.com/flutterchi…

正文完
 0