flutter 从接口获取json数据显示到页面
如题,在前端,是个很简单的ajax请求,json的显示,取值都很方便,换用dart之后,除了层层嵌套写的有点略难受之外,还有对json的使用比js要麻烦
1. 可以参照 flutter-go 先封装一下get和post请求,net_utils.dart
2. 发起请求
import 'package:flutter/material.dart';
import 'package:app/api/main.dart';
import 'package:app/utils/net_utils.dart';
import 'package:fluttertoast/fluttertoast.dart'; class SearchPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _SearchPageState();
}
} class _SearchPageState extends State<SearchPage> {
TextEditingController _searchController = new TextEditingController(); List _lists = [];
List _histryLists = []; @override
void initState() {
super.initState();
this._hotSearch(); // 这里,在页面初始化的时候请求列表接口
} void _hotSearch() {
NetUtils.get('http://localhost:3000/search').then((res) => { // 这里get后面是根据前面封装的请求来写的,自行替换url和参数
// print( res['data'])
setState(() {
_lists = res['data']; // 把从接口获取的列表赋值到_list
})
});
} void updateSearch(String keyword) {
print(keyword);
setState(() {
_searchController.text = keyword; // 这个点击搜索把值赋值到input搜索框的
});
} void _searchMusic(){ // 点击搜索
if(_searchController.text==''){
Fluttertoast.showToast(
msg: "关键词不能为空",
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
);
}else{
NetUtils.get(Api.searchApi(), {"keywords":_searchController.text}).then((res) => {
print(res['result']['songs'])
});
}
} Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TextFormField(
autofocus: true,
controller: _searchController,
style:TextStyle(color: Colors.white),
decoration: InputDecoration.collapsed(
hintText: "请输入关键词",
hintStyle: TextStyle(color: Colors.white70)),
),
actions: <Widget>[
//导航栏右侧菜单
IconButton(
icon: Icon(Icons.search, color: Colors.white),
onPressed: () {
_searchMusic();
}),
],
),
body: Container(
padding: EdgeInsets.all(20),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('历史记录'),
Icon(IconData(0xe662, fontFamily: 'iconfont')),
],
),
SizedBox(
width: 350.0,
height: 50.0,
child:
ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: _histryLists.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
child: Padding(
padding: EdgeInsets.all(5.0),
child: Chip(
label: Text(_histryLists[index]),
),
),
onTap: () => {
updateSearch(_histryLists[index])
},
);
},
)),
Padding(
padding: EdgeInsets.only(top: 30, bottom: 20),
child: Column(
children: <Widget>[
Row(
children: <Widget>[Text('热搜榜')],
),
SizedBox(
height: 520.0,
child: ListView.builder( // 这里把从接口请求的列表数据展示到页面上
shrinkWrap: true,
itemCount: _lists.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
child: Padding(
padding: EdgeInsets.all(10),
child: Flex(
direction: Axis.horizontal,
children: <Widget>[
Expanded(
flex: 1,
child: Text(
(index + 1).toString(),
style: TextStyle(
color: Colors.red, fontSize: 18),
)),
Expanded(
flex: 8,
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Text(
_lists[index]['searchWord'],
style: TextStyle(
color: Colors.grey[900],
fontSize: 16)),
),
Align(
alignment: Alignment.centerLeft,
child: Text(
_lists[index]['content'],
style: TextStyle(
color: Colors.grey[500])),
),
],
),
)
],
),
),
onTap: () =>
updateSearch(_lists[index]['searchWord']),
);
}),
)
],
),
)
],
)),
);
}
}
更多详细请看:https://github.com/leitingting08/NeteaseCloudMusicFlutter/blob/master/lib/pages/home/search.dart
flutter 从接口获取json数据显示到页面的更多相关文章
- .net从网络接口地址获取json,然后解析成对象(一)
整理代码,今天遇到一个问题,就是从一个场景接口获取json,然后解析成对象.之前的时候都好好的,这次返回的json字符串里,由于字符编码的问题,格式上不能转换.一直以为是解析的过程编码有误,试了utf ...
- Vue学习笔记十三:Vue+Bootstrap+vue-resource从接口获取数据库数据
目录 前言 SpringBoot提供后端接口 Entity类 JPA操作接口 配置文件 数据库表自动映射,添加数据 写提供数据的接口 跨域问题 前端修改 效果图 待续 前言 Vue学习笔记九的列表案例 ...
- JS-利用ajax获取json数据,并传入页面生成动态tab
封装好的:ajax.js function ajax(url, fnSucc,fnFaild){ //1[创建] if(window.XMLHttpRequest){ var oAjax = new ...
- [N久以前发布的文章]php 获取yahoo股票csv数据并封闭成为接口输出json数据
思路 先从yahoo接口获取数据,再定义接口,转化成为json输出.只供卡通网(kt5.cn)使用 stock.php 接口处理代码 <?php header("Content-Typ ...
- NodeJs本地搭建服务器,模拟接口请求,获取json数据
最近在学习Node.js,虽然就感觉学了点皮毛,感觉这个语言还不错,并且也会一步步慢慢的学着的,这里实现下NodeJs本地搭建服务器,模拟接口请求,获取json数据. 具体的使用我就不写了,这个博客写 ...
- 请求接口获取的json 字符串 前后不能有 双引号
请求接口获取的json 字符串 前后不能有 双引号 否则JSON.parse 转换会报错
- 豆瓣爬虫——通过json接口获取数据
最近在复习resqusts 爬虫模块,就重新写了一个豆瓣爬虫,这个网页从HTML 源码上来看是没有任何我想要的信息的,如下图所示: 这是网页视图,我在源码中查找影片信息,没有任何信息,如图: 由此我判 ...
- ajax获取json数据及实现跨域请求
最近想练习一下ajax获取json数据 , 首先上网找一些在线的可用来测试的接口. -----------------------------------------------------这里是接口 ...
- (六)Net Core项目使用Controller之一 c# log4net 不输出日志 .NET Standard库引用导致的FileNotFoundException探究 获取json串里的某个属性值 common.js 如何调用common.js js 筛选数据 Join 具体用法
(六)Net Core项目使用Controller之一 一.简介 1.当前最流行的开发模式是前后端分离,Controller作为后端的核心输出,是开发人员使用最多的技术点. 2.个人所在的团队已经选择 ...
随机推荐
- promethus监控nginx
一.摘要 promethues监控nginx可选两个exporter,通过nginx_exporter主要是获取nginx-status中的内建的指标,nginx自身提供status信息,较为简单,p ...
- LOJ3123 CTS2019 重复 KMP自动机、DP、多项式求逆
传送门 CTS的计数题更完辣(撒花 Orz zx2003,下面的内容在上面的博客基础上进行一定的补充. 考虑计算无限循环之后不存在子串比\(s\)字典序小的串的个数.先对串\(s\)建立KMP自动机, ...
- System.ComponentModel.Win32Exception (0x80004005): 无效的窗口句柄。
原文:System.ComponentModel.Win32Exception (0x80004005): 无效的窗口句柄. 在 WPF 获取鼠标当前坐标的时候,可能会得到一个异常:System.Co ...
- Python接口自动化基础---环境准备
安装requests模块 pip install requests request帮助文档查看 import requests print(help(requests)) Help on packag ...
- Switch开关在element-ui表格中点击没有效果解决方法
<el-table-column label="三审" align="center"> <template slot-scope=" ...
- JAVA基础之ServletContext应用
创建一个登陆的界面,并且统计次数! 导入jar包; 1. driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/java0603?u ...
- SuperTab
Tab快捷键提示功能 下载 http://www.vim.org/scripts/script.php?script_id=1643 安装 # vi supertab.vmb : UseVimball ...
- Redis3.2集群部署安装
Redis集群部署安装 Linux版本:CentOS release 6.9 Redis 版本:redis-3.2.12.tar.gz 1.执行解压命令 tar -xzf redis-3.2.12.t ...
- @ConfigurationProperties注解和@Value注解的区别
都是读取配置文件属性 1. @ConfigurationProperties(prefix = "person")读取多个属性 @Component @Configuration ...
- 绘图 Matplotlib Numpy Pandas
丈夫气力全,一个拟当千.猛气冲心出,视死亦如眠. 绘图 Matplotlib可视化是在整个数据挖掘的关键辅助工具,可以清晰的理解数据,从而调整我们的分析方法. 能将数据进行可视化,更直观的呈现使数据更 ...