利用Flutter写一个跨平台的果核APP(3)——网络请求

前言

紧接上文界面篇,上文中在构建布局的时候因为是直接将文字图片显示出来的,所以消息类Message,和日知录类One都是采用的无状态的StatelessWidget类,这次我们需要调用接口,然后将返回的数据动态的显示到那两个控件上去,StatelessWidget类已经无法满足需求了,这个时候我们需要使用Flutter提供的另一个类StatefulWidget,一旦控件继承了这个类则说明该空间是一个有状态的控件,可以进行动态更新等。

  • 推荐阅读: 《StatefulWidget》, 《State.setState》,《为您的Flutter应用程序添加交互》

到目前为止,我们只使用了无状态的widget。无状态widget从它们的父widget接收参数, 它们被存储在final型的成员变量中。 当一个widget被要求构建时,它使用这些存储的值作为参数来构建widget。 为了构建更复杂的体验 - 例如,以更有趣的方式对用户输入做出反应 - 应用程序通常会携带一些状态。 Flutter使用StatefulWidget来满足这种需求。StatefulWidget是特殊的widget,它知道如何生成State对象,然后用它来保持状态。

解析

那么该如何创建一个有状态的widget,同时又如何进行网络请求并对控件的状态进行更新呢?我们一个一个的解决。

  1. 创建一个有状态的Message控件
//消息
class Message extends StatefulWidget {@overrideMessageState createState() => new MessageState();
}class MessageState extends State<Message> {@overrideWidget build(BuildContext context) {//这里创建页面}
}
复制代码

build函数的内容其实和之前创建无状态的Message控件的是一样的,直接复制来就好

@overrideWidget build(BuildContext context) {return new Padding(padding: new EdgeInsets.all(18.0),child: new Column(children: <Widget>[new Container(child: new Row(children: <Widget>[new Icon(Icons.message,color: Colors.black26,size: 17.0,),new Container(margin: new EdgeInsets.only(left: 5.0),child: new Text('消息',style: new TextStyle(color: Color(0xFF888888)),),)],),),new Divider(color: Color(0xFF888888),),new Container(margin: new EdgeInsets.all(10.0),child: new Text("这里是消息"),),new Divider(color: Color(0xFF888888),)],),);}
复制代码
  1. 进行网络请求并更新控件 在flutter中进行网络请求有两种方式
  • 在Flutter中发起HTTP网络请求
  • 开源库——dio 在这里推荐使用第二种,dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时等。和安卓里的OkHttp类似。具体用法可以查看传送门,文档写的很详细。 回到该应用,在这里我们需要创建一个getMessage()方法,并通过get请求相应的接口,然后对返回的res进行解析即可,如下所示:
  String message = "这里是消息模块";@overridevoid initState() {super.initState();getMessage();}//获取消息void getMessage() {Dio().get(Constant.GET_MSG).then((res) {if (res.statusCode == 200) {int code = res.data['code'];if (code == 200) {String info = res.data['info'][0];print(info);setState(() {message = info;});}}});}
复制代码

说明一下:

  1. 调用setState()是至关重要的,因为它告诉框架控件的状态已经改变,控件应该重新绘制。在这里的作用就是将之前设置的message变量变为从接口中获取的变量。
  2. json的解析,推荐阅读《在 Flutter 中解析复杂的 JSON》
  3. 我们如果需要在控件一开始渲染的时候就要发送网络请求,需要在initState()函数中调用getMessage()方法

该页代码

因为日知录部分的基本上也是网络请求和动态渲染控件,道理是一致的,所以我就直接在这里贴上代码了。

import 'package:flutter/material.dart';
import 'package:flutter_guohe/common/eventBus.dart';
import 'package:dio/dio.dart';
import 'package:flutter_guohe/views/customview.dart';
import 'package:flutter_guohe/utils/constant.dart';class Today extends StatefulWidget {@overrideTodayState createState() => new TodayState();
}class TodayState extends State<Today> {//打开drawervoid openDrawer() {eventBus.fire(new EventOpenDrawer(true));}@overrideWidget build(BuildContext context) {return new MaterialApp(home: new Scaffold(appBar: new AppBar(leading: new IconButton(icon: Icon(Icons.home),onPressed: () {//打开draweropenDrawer();},),title: new Text("今日"), //设置标题内容backgroundColor: Color.fromARGB(255, 119, 136, 213), //设置appbar背景颜色centerTitle: true, //设置标题是否局中),body: new ListView(children: <Widget>[new Header(), //头部new BigDivider(),new TodayKb(), //今日课表new BigDivider(),new Message(), //消息new BigDivider(),new One() //日知录],),),);}
}//首页的头部信息
class Header extends StatelessWidget {@overrideWidget build(BuildContext context) {return new Container(height: 100.0,margin: new EdgeInsets.all(8.0),child: new Row(children: <Widget>[new Expanded(child: new Column(children: <Widget>[//头像new Container(width: 60.0,height: 60.0,margin: new EdgeInsets.all(8.0),decoration: BoxDecoration(image: DecorationImage(image: new AssetImage('assets/imgs/ic_menu_score.png'),//从Assets加载图片fit: BoxFit.cover,),shape: BoxShape.circle,),),new Text('查成绩',textAlign: TextAlign.center,)],),flex: 1,),new Expanded(child: new Column(children: <Widget>[//头像new Container(width: 60.0,height: 60.0,margin: new EdgeInsets.all(8.0),decoration: BoxDecoration(image: DecorationImage(image: new AssetImage('assets/imgs/ic_menu_pe.png'),//从Assets加载图片fit: BoxFit.cover,),shape: BoxShape.circle,),),new Text('查体育',textAlign: TextAlign.center,)],),flex: 1,),new Expanded(child: new Column(children: <Widget>[//头像new Container(width: 60.0,height: 60.0,margin: new EdgeInsets.all(8.0),decoration: BoxDecoration(image: DecorationImage(image: new AssetImage('assets/imgs/ic_menu_bus.png'),//从Assets加载图片fit: BoxFit.cover,),shape: BoxShape.circle,),),new Text('查校车',textAlign: TextAlign.center,)],),flex: 1,),new Expanded(child: new Column(children: <Widget>[//头像new Container(width: 60.0,height: 60.0,margin: new EdgeInsets.all(8.0),decoration: BoxDecoration(image: DecorationImage(image: new AssetImage('assets/imgs/ic_menu_system.png'),//从Assets加载图片fit: BoxFit.cover,),shape: BoxShape.circle,),),new Text('校园系统',textAlign: TextAlign.center,)],),flex: 1,),new Expanded(child: new Column(children: <Widget>[//头像new Container(width: 60.0,height: 60.0,margin: new EdgeInsets.all(8.0),decoration: BoxDecoration(image: DecorationImage(image: new AssetImage('assets/imgs/ic_menu_more.png'),//从Assets加载图片fit: BoxFit.cover,),shape: BoxShape.circle,),),new Text('更多',textAlign: TextAlign.center,)],),flex: 1,),],),);}
}//今日课表
class TodayKb extends StatefulWidget {@overrideTodayKbState createState() => new TodayKbState();
}class TodayKbState extends State<TodayKb> {@overrideWidget build(BuildContext context) {//跳转至课表_toKb() {print('跳转至课表');}return new Padding(padding: new EdgeInsets.all(18.0),child: new Column(children: <Widget>[new Container(child: new Row(children: <Widget>[new Icon(Icons.camera,color: Colors.black26,size: 17.0,),new Container(margin: new EdgeInsets.only(left: 5.0),child: new Text('今日课表',style: new TextStyle(color: Color(0xFF888888)),),)],),),new Divider(color: Color(0xFF888888),),new Container(margin: new EdgeInsets.only(top: 30.0, bottom: 2.0),child: new Text("今天居然没有课~" + "\uD83D\uDE01"),),new GestureDetector(child: new Container(margin: new EdgeInsets.only(top: 30.0, bottom: 2.0),child: new Text('点我查看完整课表',style: new TextStyle(color: Color(0xFF888888,),fontSize: 12.0)),),onTap: _toKb,),],),);}
}//消息
class Message extends StatefulWidget {@overrideMessageState createState() => new MessageState();
}class MessageState extends State<Message> {String message = "这里是消息模块";@overridevoid initState() {super.initState();getMessage();}//获取消息void getMessage() {Dio().get(Constant.GET_MSG).then((res) {if (res.statusCode == 200) {int code = res.data['code'];if (code == 200) {String info = res.data['info'][0];print(info);setState(() {message = info;});}}});}@overrideWidget build(BuildContext context) {return new Padding(padding: new EdgeInsets.all(18.0),child: new Column(children: <Widget>[new Container(child: new Row(children: <Widget>[new Icon(Icons.message,color: Colors.black26,size: 17.0,),new Container(margin: new EdgeInsets.only(left: 5.0),child: new Text('消息',style: new TextStyle(color: Color(0xFF888888)),),)],),),new Divider(color: Color(0xFF888888),),new Container(margin: new EdgeInsets.all(10.0),child: new Text(message),),new Divider(color: Color(0xFF888888),)],),);}
}//日知录
class One extends StatefulWidget {@overrideOneState createState() => new OneState();
}class OneState extends State<One> {String date = "2018/09/14";String imgUrl = 'http://image.wufazhuce.com/Fn5E1UnrcvN0jwFRiOtDZ2WnQa4N';String imgAuthor = "Fahmi Ramadhan";String imgKind = "摄影";String url = "http://m.wufazhuce.com/one/2202";String word = "恋爱不是用谈的,是坠入的。";String wordFrom = "《寂寞东京铁塔》";//获取日知录的内容void getOneContent() {FormData formData = new FormData.from({"TransCode": "030111", "OpenId": "123456789", "Body": "123456789"});Dio().post(Constant.ONE, data: formData).then((res) {setState(() {date = res.data['Body']['date'].toString().split(" ")[0].replaceAll("-", "/");imgUrl = res.data['Body']['img_url'];imgAuthor = res.data['Body']['img_author'];imgKind = res.data['Body']['img_kind'];url = res.data['Body']['url'];word = res.data['Body']['word'];wordFrom = res.data['Body']['word_from'];});});}@overridevoid initState() {// TODO: implement initStatesuper.initState();getOneContent();}@overrideWidget build(BuildContext context) {return new Padding(padding: new EdgeInsets.all(18.0),child: new Column(children: <Widget>[new Container(child: new Row(children: <Widget>[new Icon(Icons.email,color: Colors.black26,size: 17.0,),new Container(margin: new EdgeInsets.only(left: 5.0),child: new Text('日知录',style: new TextStyle(color: Color(0xFF888888)),),)],),),new Divider(color: Color(0xFF888888),),new Container(margin: new EdgeInsets.all(10.0),child: new Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[new Text(date,style: new TextStyle(color: Color(0xFF888888)),),new Margin(indent: 6.0),new Image(image: new NetworkImage(imgUrl)),new Margin(indent: 6.0),new Text(imgAuthor + " | " + imgKind,style: new TextStyle(color: Color(0xFF888888)),),new Margin(indent: 6.0),new Text(word,textAlign: TextAlign.center,style: new TextStyle(color: Color(0xFF888888)),),new Margin(indent: 6.0),new Text(wordFrom,style: new TextStyle(color: Color(0xFF888888)),)],),),new Divider(color: Color(0xFF888888),)],),);}
}
复制代码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/277259.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2019 7 12

ICMP 协议封装 ICMP 协议属于网络层协议 ICMP 数据的封装过程 ICMP头部 ICMP数据 IP头部 上层数据&#xff08;ICMP报文&#xff09; 帧头部 上 层 数 据 帧尾部 ping命令 C&#xff1a;>ping [t] [-l 字节数] [-i] ip_address | target…

android layer-list,Android layer-list的属性和使用具体解释

Android layer-list的属性和使用具体解释。layer-list是用来多个图层堆叠显示的&#xff0c;借这个特性能够做一些特别的效果(比方&#xff1a;阴影、以下的效果等)&#xff0c;也能够投机取巧。1.代码片2.布局代码和效果图 (一定要注意在使用RadioGroup的时候要记的写RadioBut…

上传文件夹

前台<% Page language"c#" Codebehind"ZJSJKSC.aspx.cs" AutoEventWireup"false" Inherits"DDTYDB.Module.WJGL.ZJSJKSC" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><HTML> <…

关于swiper的tab(选项卡)中设置了autoHeight没有效果解决

autoHeight属性使用看官网的示例&#xff1a;https://www.swiper.com.cn/api/parameters/294.html swiper的选项卡结构查看&#xff1a;https://www.swiper.com.cn/demo/indexsample/ swiper的tab的一般DOM节点为&#xff1a; <body> <div class"tabs"> …

UrlEncode

ASP.NET 快速入门教程/使用服务器控件/执行页导航&#xff08;方案 2&#xff09;里有两段代码不是很清楚。 UrlEncode前面的相关内容为何有点不同呢&#xff1f; 源页面向目标页面发送参数的代码。<script language"C#" runat"server"> voi…

android html邮件 messagecompose,android email 转发附件丢失问题

在MessageCompose.java中将else if (ACTION_REPLY.equals(mAction)- || ACTION_REPLY_ALL.equals(mAction)- || ACTION_FORWARD.equals(mAction)) {}中ACTION_FORWARD提取成&#xff1a;else if(ACTION_FORWARD.equals(mAction)) …

数据库字段属性配置工具界面[用于代码生成]

在CodeSmith中为了实现对数据库中表字段的选择和针对字段来设置属性&#xff0c;决定用XML文件作为中间数据的交换方式&#xff0c;在CodeSmith中读取数据库对象的信息不再使用SchemaExplorer来读取&#xff0c;而是转为直接对XML文件的读取。<?xml:namespace prefix o ns…

Codeforces 892E Envy

问题描述 小Q正在玩一个叠塔的游戏&#xff0c;游戏的目标是叠出尽可能高的塔。在游戏中&#xff0c;一共有n张矩形卡片&#xff0c;其中第i张卡片的 长度为a_i&#xff0c;宽度为b_i。小Q需要把所有卡片按一定顺序叠成一座塔&#xff0c;要求对于任意一个矩形&#xff0c;它的…

Zookeeper环境安装

源码包下载&#xff1a; http://archive.apache.org/dist/zookeeper/zookeeper-3.4.10 集群环境&#xff1a; master 192.168.1.99 slave1 192.168.1.100 slave2 192.168.1.101 下载安装包&#xff1a; # Mater wget http://archive.apache.org/dist/zookeeper/zookeeper-3.4.1…

鸿蒙系统用没有安卓的代码,套壳?不存在!纯鸿蒙系统不含任何安卓代码,其他手机厂商可使用...

众所周知&#xff0c;华为的鸿蒙系统已经应用于许多华为机型上&#xff0c;例如Mate40、MataX2等&#xff0c;同时不少家电厂商也和华为合作推出了基于鸿蒙的终端设备&#xff0c;比如美的、老板等。那么&#xff0c;和华为处于竞争关系的手机厂商可以使用鸿蒙系统吗&#xff1…

出来乍到

第一篇&#xff0c;还没想到写什么东西&#xff0c;比空的好&#xff0c;先这么挂一下把。转载于:https://www.cnblogs.com/Carlwave/archive/2006/01/24/322413.html

Java消息队列总结只需一篇解决ActiveMQ、RabbitMQ、ZeroMQ、Kafka

一、消息队列概述 消息队列中间件是分布式系统中重要的组件&#xff0c;主要解决应用解耦&#xff0c;异步消息&#xff0c;流量削锋等问题&#xff0c;实现高性能&#xff0c;高可用&#xff0c;可伸缩和最终一致性架构。目前使用较多的消息队列有ActiveMQ&#xff0c;RabbitM…

一种快速统计SQL Server每个表行数的方法

我们都知道用聚合函数count()可以统计表的行数。如果需要统计数据库每个表各自的行数(DBA可能有这种需求)&#xff0c;用count()函数就必须为每个表生成一个动态SQL语句并执行&#xff0c;才能得到结果。以前在互联网上看到有一种很好的解决方法&#xff0c;忘记出处了&#xf…

android 小黄车首页,android采用MVP漫画APP、适配刘海屏、小黄车主界面、录音波浪动画、综合APP等源码...

Android精选源码Android优质博客为什么组件化 随着移动互联网的发展&#xff0c;或许中小型项目还可以用单工程MVC/MVP/MVVM的架构来完成&#xff0c;但当项目到了一定程度之后&#xff0c;编译时间 原来越长&#xff0c;测试或者开发任何一个模块功能都需要整个项目重启运行。…

[HEOI2012]采花

题目描述 萧薰儿是古国的公主&#xff0c;平时的一大爱好是采花。 今天天气晴朗&#xff0c;阳光明媚&#xff0c;公主清晨便去了皇宫中新建的花园采花。 花园足够大&#xff0c;容纳了n朵花&#xff0c;花有c种颜色&#xff08;用整数1-c表示&#xff09;&#xff0c;且花是排…

修改SQL server数据库中的逻辑文件名

使用 FILE_NAME 函数可以返回给定文件标识 (ID) 号的逻辑文件名如下 下例返回 file_ID 为 1 的文件名&#xff08;master 数据库文件&#xff09;。 1USEmaster2SELECTFILE_NAME(1)当我们进行从一个备份中还原数据库时&#xff0c;数据库的逻辑文件名是不会改变的。 可用 ALTER…

java根据模板生成PDF

首先你的制作一个pdf模板&#xff1a; 1.先用word做出模板界面 画单元格的时候需要考虑值的长度&#xff0c;像这里的状态可能会很长 2.文件另存为pdf格式文件 使用福昕PDF 打开&#xff0c;添加文本&#xff0c;以及需要添加值的地方&#xff0c;设置文本域&#xff0c;这个就…

android bilibili搜索框,仿bilibili搜索框效果(三句代码实现)

SearchDialog仿bilibili搜索框效果(只需要三句话即可实现)先看预览图(转换后有一点点失真):前言1,支持搜索历史(已经做了数据库存储了)2,基本与bilibili的搜索效果差不多了3,需要修改更多内容可以下载library自己修改4,本人非大牛,有不妥之处请Issues指出,谢谢5,参考了该po的文…

元璟资本陈洪亮解析人货场融合 消费者变成“合作者”

一年一度的云栖大会是新科技大放异彩的舞台&#xff0c;而创业者们同样聚集于此&#xff0c;探讨前沿的商业模式。 在今日举行的“云栖大会 - 阿里云创新中心年度盛典”上&#xff0c;元璟资本合伙人陈洪亮发表演讲&#xff0c;他从新消费和新零售的诸多创新现象出发&#xff0…

通用数据库显示程序

数据库显示程序,能调任意库,任意字段,多关键字搜索,自动分页. 阿余经常写一些数据库相关的程序,当然离不开显示库中的数据了,说实话,做这样的程序真是无聊啊,所以,阿余就想写个函数,一个通用的数据库显示函数.要求如下: 1. 能显示指定的字段,当然,字段名和显示的文字可以不一样…