当前位置:网站首页>[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 )
边栏推荐
- Qt之QComboBox添加QCheckBox(下拉列表框插入复选框,含源码+注释)
- [fluent] listview list (map method description of list set | vertical list | horizontal list | code example)
- GBase 8c系统表-pg_auth_members
- Flink CDC mongoDB 使用及Flink sql解析monggo中复杂嵌套JSON数据实现
- Producer consumer model based on thread pool (including blocking queue)
- 内存池(内核角度理解new开辟空间的过程)
- Codeforces Round #418 (Div. 2) D. An overnight dance in discotheque
- Unrecognized SSL message, plaintext connection?
- Gbase 8C system table PG_ cast
- 《MATLAB 神经网络43个案例分析》:第43章 神经网络高效编程技巧——基于MATLAB R2012b新版本特性的探讨
猜你喜欢
[fluent] JSON model conversion (JSON serialization tool | JSON manual serialization | writing dart model classes according to JSON | online automatic conversion of dart classes according to JSON)
Matlab tips (24) RBF, GRNN, PNN neural network
怎么将yolov5中的PANet层改为BiFPN
Build a private cloud disk cloudrev
Summary of interview project technology stack
Detailed analysis of micro service component sentinel (hystrix)
返回一个树形结构数据
"Analysis of 43 cases of MATLAB neural network": Chapter 43 efficient programming skills of neural network -- Discussion Based on the characteristics of the new version of MATLAB r2012b
[shutter] bottom navigation bar page frame (bottomnavigationbar bottom navigation bar | pageview sliding page | bottom navigation and sliding page associated operation)
搭建私有云盘 cloudreve
随机推荐
Tongda OA homepage portal workbench
Gbase 8C function / stored procedure definition
Startup mode and scope builder of collaboration in kotlin
Cancellation of collaboration in kotlin, side effects of cancellation and overtime tasks
Monitoring and management of JVM
Awk from entry to burial (1) awk first meeting
Flink CDC mongoDB 使用及Flink sql解析monggo中复杂嵌套JSON数据实现
JS的装箱和拆箱
Random Shuffle attention
Unrecognized SSL message, plaintext connection?
Hcip137-147 title + analysis
【Flutter】shared_ Preferences local storage (introduction | install the shared_preferences plug-in | use the shared_preferences process)
GBase 8c触发器(三)
Mathematical statistics -- Sampling and sampling distribution
Exception handling in kotlin process
《MATLAB 神经网络43个案例分析》:第43章 神经网络高效编程技巧——基于MATLAB R2012b新版本特性的探讨
Current situation and future of Web3 in various countries
【翻译】具有集中控制平面的现代应用负载平衡
Packing and unpacking of JS
Gbase 8C system table PG_ database