flutter dio网络请求和listview显示
2023-09-14 09:04:29 时间
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)),
)
],
))));
}
}
相关文章
- flutter系列之:Material中的3D组件Card
- Flutter之GetX依赖注入使用详解
- 重走Flutter状态管理之路—Riverpod进阶篇
- [- Flutter 数据&状态篇 -] setState
- 【Flutter 小知识】震动反馈 HapticFeedback
- flutter系列之:永远不用担心组件溢出的Wrap
- Flutter 组件集录 | 从图标按钮看组件封装
- Flutter Web:刷新与后退问题
- Flutter 绘制探索 | 饼状图的绘制与事件
- 【错误记录】Flutter 设备连接显示 Loading... ( 断网 | 删除 flutter/bin/cache/lockfile 文件 )
- 【错误记录】Flutter 环境安装相关问题 ( 执行 flutter doctor 命令后续错误处理 )
- 【错误记录】命令行创建 Flutter 应用报错 pub get failed (server unavailable) -- attempting retry 1 in 1 second...
- 【Flutter】Flutter 布局组件 ( 布局组件简介 | Row 组件 | Column 组件 | SizedBox 组件 | ClipOval 组件 )
- 【错误记录】Flutter 报错 ( Because xx depends on flutter_driver any from sdk which depends on args 1.6.0 )
- 【Flutter】Flutter Gallery 官方示例简介 ( 学习示例 | 邮件应用 | 零售应用 | 理财应用 | 旅行应用 | 新闻应用 | 自适应布局应用 )
- 【Flutter】ExpansionTile 可折叠列表
- 【Flutter】Flutter 启动白屏问题 ( 问题描述 | 在 launch_background.xml 中设置启动过渡 UI )
- 【Flutter】Android、Flutter 折叠屏适配 ( 展开大屏 | 折叠主屏 | 折叠副屏 | 静态展示 | 动态热切换适配 | 拉伸布局 | X 轴自适应适配 | 布局重构 )
- 只需浏览器!在线完成Flutter从编程到打包全过程