当前位置:网站首页>[flutter] example of asynchronous programming code between future and futurebuilder (futurebuilder constructor setting | handling flutter Chinese garbled | complete code example)
[flutter] example of asynchronous programming code between future and futurebuilder (futurebuilder constructor setting | handling flutter Chinese garbled | complete code example)
2022-07-03 02:32:00 【Programmer community】
List of articles
- One 、FutureBuilder brief introduction
- Two 、 Handle Flutter The Chinese characters in
- 3、 ... and 、 Complete code example
- Four 、 Related resources
One 、FutureBuilder brief introduction
FutureBuilder The essence is components : FutureBuilder After construction , Will automatically perform asynchronous operations , And back to Widget Components , therefore FutureBuilder It's also a component , Display components of different styles in different states ;
FutureBuilder Generic settings : FutureBuilder The generic , Represents the result of asynchronous call Future The generic , That is, the format of the returned result ; FutureBuilder<CommonModel> Represents an asynchronous call Future The return value of Future<CommonModel> ;
Future<T> future Parameter setting : This is to set the asynchronous operation method , Below httpGet() Method , It's a return Future<CommonModel> Method of type , Can be set directly to FutureBuilder Constructor as a parameter ;
/// call Http Get Method , Get the server 's json data Future<CommonModel> httpGet() async {
//var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1'); var url = Uri.parse('https://www.devio.org/io/flutter_app/json/test_common_model.json'); // Asynchronous requests , Get remote server information final response = await http.get(url); /// Deal with Chinese code Utf8Decoder utf8decoder = Utf8Decoder(); /// Binary Byte The data to UTF-8 Format encoding , Get the encoded string String responseString = utf8decoder.convert(response.bodyBytes); // take json The string information is converted to Map<String, dynamic> Key value pair information of type Map<String, dynamic> jsonMap = json.decode(responseString); return CommonModel.fromJson(jsonMap); }@required AsyncWidgetBuilder<T> builder Parameters are parameters that must be set , This parameter is AsyncWidgetBuilder<T> type Methods :
typedef AsyncWidgetBuilder<T> = Widget Function(BuildContext context, AsyncSnapshot<T> snapshot);The parameters passed in are as follows : Write an anonymous function by yourself , Parameter is BuildContext context, AsyncSnapshot<T> snapshot , The return value is Widget ;
(BuildContext context, AsyncSnapshot<CommonModel> snapshot){
return Text("");}In the above Anonymous functions in , Start with AsyncSnapshot<CommonModel> snapshot Parameters for various operations , BuildContext context Parameters are not used this time ;
adopt snapshot.connectionState You can get the status of the current asynchronous request , You can display the progress bar in the request , After the request, determine whether the request is successful , If something goes wrong , An error message is displayed , If the request succeeds , Then the information of successful request will be displayed ;
No matter what , Finally, you have to return a Widget Components ;
FutureBuilder Constructor complete code example :
@override Widget build(BuildContext context) {
return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("HTTP Get request "), ), // Linear layout Column body: FutureBuilder<CommonModel>( // Set the method of asynchronous invocation future: httpGet(), /// Receive the following types of objects /// typedef AsyncWidgetBuilder<T> = Widget Function(BuildContext context, AsyncSnapshot<T> snapshot); builder: (BuildContext context, AsyncSnapshot<CommonModel> snapshot){
/// Judge AsyncSnapshot Connection state of switch(snapshot.connectionState){
case ConnectionState.none: return Text(" Unconnected "); case ConnectionState.waiting: /// Return a progress bar return Center(child: CircularProgressIndicator(),); case ConnectionState.active: /// active , Return a progress bar return Text(""); case ConnectionState.done: /// End of request , If something goes wrong , Error message returned /// If the request succeeds , Return the data requested from the network if(snapshot.hasError) {
return Text(" request was aborted , Error message : ${snapshot.error}", style: TextStyle(color: Colors.red),); } else {
return Text(" The request is successful , pick up information : ${snapshot.data?.url}", style: TextStyle(color: Colors.green),); } } }, ), ), ); }Two 、 Handle Flutter The Chinese characters in
The data is based on UTF-8 Format to encode , Only with UTF-8 Format for decoding ;
establish Utf8Decoder decoder ,
/// Deal with Chinese code Utf8Decoder utf8decoder = Utf8Decoder();Calling the decoder's convert Method , Incoming raw binary data , Note that it is data of byte array type ;
/// Binary Byte The data to UTF-8 Format encoding , Get the encoded string String responseString = utf8decoder.convert(response.bodyBytes);The returned value is the string text information encoded correctly ;
Complete code example :
/// call Http Get Method , Get the server 's json data Future<CommonModel> httpGet() async {
//var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1'); var url = Uri.parse('https://www.devio.org/io/flutter_app/json/test_common_model.json'); // Asynchronous requests , Get remote server information final response = await http.get(url); /// Deal with Chinese code Utf8Decoder utf8decoder = Utf8Decoder(); /// Binary Byte The data to UTF-8 Format encoding , Get the encoded string String responseString = utf8decoder.convert(response.bodyBytes); // take json The string information is converted to Map<String, dynamic> Key value pair information of type Map<String, dynamic> jsonMap = json.decode(responseString); return CommonModel.fromJson(jsonMap); }3、 ... and 、 Complete code example
import 'package:flutter/material.dart';import 'package:http/http.dart' as http;/// json serialize , Deserialization package import 'dart:convert';void main() {
runApp(MyApp());}class MyApp extends StatefulWidget {
const MyApp({
Key? key}) : super(key: key); @override _MyAppState createState() => _MyAppState();}class _MyAppState extends State<MyApp> {
/// HTTP GET Return value String httpGetResult = ""; /// call Http Get Method , Get the server 's json data Future<CommonModel> httpGet() async {
//var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1'); var url = Uri.parse('https://www.devio.org/io/flutter_app/json/test_common_model.json'); // Asynchronous requests , Get remote server information final response = await http.get(url); /// Deal with Chinese code Utf8Decoder utf8decoder = Utf8Decoder(); /// Binary Byte The data to UTF-8 Format encoding , Get the encoded string String responseString = utf8decoder.convert(response.bodyBytes); // take json The string information is converted to Map<String, dynamic> Key value pair information of type Map<String, dynamic> jsonMap = json.decode(responseString); return CommonModel.fromJson(jsonMap); } @override Widget build(BuildContext context) {
return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("HTTP Get request "), ), // Linear layout Column body: FutureBuilder<CommonModel>( // Set the method of asynchronous invocation future: httpGet(), /// Receive the following types of objects /// typedef AsyncWidgetBuilder<T> = Widget Function(BuildContext context, AsyncSnapshot<T> snapshot); builder: (BuildContext context, AsyncSnapshot<CommonModel> snapshot){
/// Judge AsyncSnapshot Connection state of switch(snapshot.connectionState){
case ConnectionState.none: return Text(" Unconnected "); case ConnectionState.waiting: /// Return a progress bar return Center(child: CircularProgressIndicator(),); case ConnectionState.active: /// active , Return a progress bar return Text(""); case ConnectionState.done: /// End of request , If something goes wrong , Error message returned /// If the request succeeds , Return the data requested from the network if(snapshot.hasError) {
return Text(" request was aborted , Error message : ${snapshot.error}", style: TextStyle(color: Colors.red),); } else {
return Text(" The request is successful , pick up information : ${snapshot.data?.url}", style: TextStyle(color: Colors.green),); } } }, ), ), ); }}class CommonModel {
final String? icon; final String? title; final String? url; final String? statusBarColor; final bool? hideAppBar; CommonModel({
this.icon, this.title, this.url, this.statusBarColor, this.hideAppBar}); factory CommonModel.fromJson(Map<String, dynamic> json) {
return CommonModel( icon: json['icon'], title: json['title'], url: json['url'], statusBarColor: json['statusBarColor'], hideAppBar: json['hideAppBar'], ); }}Execution results :

Four 、 Related resources
Reference material :
- Flutter Official website : https://flutter.dev/
- Flutter Plug in download address : https://pub.dev/packages
- Flutter Developing documents : https://flutter.cn/docs ( Strongly recommend )
- official GitHub Address : https://github.com/flutter
- Flutter The Chinese community : https://flutter.cn/
- Flutter Practical tutorial : https://flutter.cn/docs/cookbook
- Flutter CodeLab : https://codelabs.flutter-io.cn/
- Dart Chinese document : https://dart.cn/
- Dart Developer website : https://api.dart.dev/
- Flutter Chinese net : https://flutterchina.club/ , http://flutter.axuer.com/docs/
- Flutter Related issues : https://flutterchina.club/faq/ ( It is recommended to watch it at the introductory stage )
- GitHub Upper Flutter Open source examples : https://download.csdn.net/download/han1202012/15989510
- Flutter Practical e-books : https://book.flutterchina.club/chapter1/
- Dart Language practice website : https://dartpad.dartlang.org/
Important topics :
- Flutter Animation reference documentation : https://flutterchina.club/animations/
Blog source download :
GitHub Address : https://github.com/han1202012/flutter_http( Keep updating with the progress of the blog , There may not be the source code of this blog )
Blog source snapshot : https://download.csdn.net/download/han1202012/21528472 ( The source code snapshot of this blog , You can find the source code of this blog )
边栏推荐
- 【翻译】具有集中控制平面的现代应用负载平衡
- [hcia]no.15 communication between VLANs
- Gbase 8C system table PG_ constraint
- 微服务组件Sentinel (Hystrix)详细分析
- 面试八股文整理版
- UDP receive queue and multiple initialization test
- Wechat - developed by wechat official account Net core access
- GBase 8c 函数/存储过程定义
- 【CodeForces】CF1338A - Powered Addition【二进制】
- Matlab tips (24) RBF, GRNN, PNN neural network
猜你喜欢
【ROS进阶篇】第六讲 ROS中的录制与回放(rosbag)

Use go language to realize try{}catch{}finally

面试项目技术栈总结

Error invalid bound statement (not found): com ruoyi. stock. mapper. StockDetailMapper. XXXX solution

【Flutter】shared_ Preferences local storage (introduction | install the shared_preferences plug-in | use the shared_preferences process)

awk从入门到入土(0)awk概述

4. Classes and objects

easyExcel

Awk from introduction to earth (0) overview of awk

Thread safe singleton mode
随机推荐
Apple releases MacOS 11.6.4 update: mainly security fixes
通达OA 首页门户工作台
GBase 8c 函数/存储过程参数(二)
GBase 8c系统表-pg_collation
Awk from getting started to being buried (2) understand the built-in variables and the use of variables in awk
The data in servlet is transferred to JSP page, and the problem cannot be displayed using El expression ${}
Unrecognized SSL message, plaintext connection?
awk从入门到入土(2)认识awk内置变量和变量的使用
Gbase 8C trigger (II)
[hcia]no.15 communication between VLANs
[Hcia]No.15 Vlan间通信
Gbase 8C system table PG_ authid
Gbase 8C function / stored procedure parameters (II)
[codeforces] cf1338a - Powered addition [binary]
Gbase 8C function / stored procedure definition
QT qcombobox add qccheckbox (drop-down list box insert check box, including source code + comments)
[Flutter] dart: class; abstract class; factory; Class, abstract class, factory constructor
人脸识别6- face_recognition_py-基于OpenCV使用Haar级联与dlib库进行人脸检测及实时跟踪
Job object of collaboration in kotlin
Codeforces Round #418 (Div. 2) D. An overnight dance in discotheque