当前位置:网站首页>[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 )
边栏推荐
- Hcip137-147 title + analysis
- Gbase 8C function / stored procedure definition
- Error invalid bound statement (not found): com ruoyi. stock. mapper. StockDetailMapper. XXXX solution
- Cvpr2022 remove rain and fog
- Monitoring and management of JVM
- Gbase 8C system table PG_ aggregate
- Awk from getting started to getting into the ground (3) the built-in functions printf and print of awk realize formatted printing
- Producer consumer model based on thread pool (including blocking queue)
- JS的装箱和拆箱
- GBase 8c 触发器(一)
猜你喜欢
![[shutter] bottom navigation bar page frame (bottomnavigationbar bottom navigation bar | pageview sliding page | bottom navigation and sliding page associated operation)](/img/6e/67bc187a89fb9125856c78c89f7bfb.gif)
[shutter] bottom navigation bar page frame (bottomnavigationbar bottom navigation bar | pageview sliding page | bottom navigation and sliding page associated operation)

SPI机制

The data in servlet is transferred to JSP page, and the problem cannot be displayed using El expression ${}

HW-初始准备

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

How to change the panet layer in yolov5 to bifpn

Distributed transaction solution

8 free, HD, copyright free video material download websites are recommended
![[hcia]no.15 communication between VLANs](/img/59/a467c5920cbccb72040f39f719d701.jpg)
[hcia]no.15 communication between VLANs

Servlet中数据传到JSP页面使用el表达式${}无法显示问题
随机推荐
Monitoring and management of JVM
通达OA 首页门户工作台
Exception handling in kotlin process
GBase 8c 函数/存储过程参数(二)
QT qcombobox add qccheckbox (drop-down list box insert check box, including source code + comments)
[fluent] listview list (map method description of list set | vertical list | horizontal list | code example)
内存池(内核角度理解new开辟空间的过程)
[hcia]no.15 communication between VLANs
Javescript 0.1 + 0.2 = = 0.3 problem
基于can总线的A2L文件解析(2)
通达OA v12流程中心
[tutorial] chrome turns off cross domain policies CORS and samesite, and brings cookies across domains
Gbase 8C system table PG_ constraint
Gbase 8C system table PG_ amop
Wechat - developed by wechat official account Net core access
Startup mode and scope builder of collaboration in kotlin
Gbase 8C system table PG_ am
Machine learning process and method
Gbase 8C system table PG_ cast
Unrecognized SSL message, plaintext connection?