利用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.pswp.cn/news/277259.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/277259.shtml
英文地址,請注明出處:http://en.pswp.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. 能顯示指定的字段,當然,字段名和顯示的文字可以不一樣…