Flutter 学习第二课(Dio网络请求简单用法和数据适配)

Flutter 学习第二课(Dio网络请求简单用法和数据适配)
文章图片

主页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 data; //构造方法,初始化时传入空数组[]即可GoodListModel({required this.data,this.code, this.message}); //通过传入json数据转换成数据模型GoodListModel.fromJson(Map json) { code = json['code']; message = json['message']; if (json['data'] != null) { data = https://www.it610.com/article/[]; //循环迭代Json数据冰将其每一项数据转成GoodModel json['data'].forEach((v) { data.add(GoodModel.fromJson(v)); }); } }//将数据模型转成Json Map toJson() { final Map data = https://www.it610.com/article/Map(); 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 json) { image = json['image']; oriPrice = json['oriPrice']; presentPrice = json['presentPrice']; name = json['name']; goodsId = json['goodsId']; }//将数据模型转成Json Map toJson() { final Map data = https://www.it610.com/article/new Map(); 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 { //初始化数据模型 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 = https://www.it610.com/article/{'shopId', '001'}; //调用请求方法传入url和表单数据 await request(url, formData: formData).then((value) { //返回数据进行Json解码 var data = https://www.it610.com/article/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: [ //返回商品图片 _goodsImage(newList, index), SizedBox( width: 10, ), //右侧使用垂直布局 Column( children: [ _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: [ 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获取不到数据
我这个数据请求接口有问题,我只是练习一下数据请求怎么处理的流程
【Flutter 学习第二课(Dio网络请求简单用法和数据适配)】Dio的github地址:https://github.com/flutterchi...

    推荐阅读