当前位置:网站首页>[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 )
边栏推荐
- [translation] flux is safe. Gain more confidence through fuzzy processing
- Restcloud ETL cross database data aggregation operation
- 通达OA 首页门户工作台
- Gbase 8C function / stored procedure definition
- Awk from entry to burial (1) awk first meeting
- RestCloud ETL 跨库数据聚合运算
- Gbase 8C function / stored procedure parameters (I)
- 【教程】chrome关闭跨域策略cors、samesite,跨域带上cookie
- Job object of collaboration in kotlin
- require.context
猜你喜欢

Principle and application of database

Thread safe singleton mode

定了,就选它

"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

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

怎么将yolov5中的PANet层改为BiFPN

random shuffle注意

How to change the panet layer in yolov5 to bifpn

《MATLAB 神经网络43个案例分析》:第43章 神经网络高效编程技巧——基于MATLAB R2012b新版本特性的探讨

Random shuffle note
随机推荐
GBase 8c 函数/存储过程参数(一)
easyExcel
require. context
Principle and application of database
random shuffle注意
5. File operation
JS的装箱和拆箱
Su Shimin: 25 principles of work and life
GBase 8c系统表-pg_auth_members
RestCloud ETL 跨库数据聚合运算
awk从入门到入土(0)awk概述
GBase 8c系统表pg_database
Awk from entry to burial (1) awk first meeting
COM和CN
[Flutter] dart: class;abstract class;factory;类、抽象类、工厂构造函数
Word word word
Gbase 8C system table PG_ constraint
How to change the panet layer in yolov5 to bifpn
The Linux server needs to install the agent software EPS (agent) database
Compréhension simple de SVG