Flutter异步编程 http网络请求数据
2024-09-03 07:44:57
import 'dart:convert'; import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async'; class HttpDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('HttpDemo'),
elevation: 0.0,
),
body: HttpDemoHome(),
);
}
} class HttpDemoHome extends StatefulWidget {
@override
_HttpDemoHomeState createState() => _HttpDemoHomeState();
} class _HttpDemoHomeState extends State<HttpDemoHome> {
@override
void initState() {
super.initState();
// fetchPosts()
// .then((value) => print(value)); // final post = {
// 'title': 'hello',
// 'description': 'nice to meet you.',
// }; // print(post['title']);
// print(post['description']); // final postJson = json.encode(post);
// print(postJson); // final postJsonConverted = json.decode(postJson);
// print(postJsonConverted['title']);
// print(postJsonConverted['description']);
// print(postJsonConverted is Map); // final postModel = Post.fromJson(postJsonConverted);
// print('title: ${postModel.title}, description: ${postModel.description}'); // print('${json.encode(postModel)}');
} Future<List<Post>> fetchPosts() async {
final response =
await http.get('https://resources.ninghao.net/demo/posts.json'); // print('statusCode: ${response.statusCode}');
// print('body: ${response.body}'); if (response.statusCode == 200) {
final responseBody = json.decode(response.body);
List<Post> posts = responseBody['posts']
.map<Post>((item) => Post.fromJson(item))
.toList(); return posts;
} else {
throw Exception('Failed to fetch posts.');
}
} @override
Widget build(BuildContext context) {
return FutureBuilder(
future: fetchPosts(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
print('data: ${snapshot.data}');
print('connectionState: ${snapshot.connectionState}'); if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text('loading...'),
);
} return ListView(
children: snapshot.data.map<Widget>((item) {
return ListTile(
title: Text(item.title),
subtitle: Text(item.author),
leading: CircleAvatar(
backgroundImage: NetworkImage(item.imageUrl),
),
);
}).toList(),
);
},
);
}
} class Post {
final int id;
final String title;
final String description;
final String author;
final String imageUrl; Post(
this.id,
this.title,
this.description,
this.author,
this.imageUrl,
); Post.fromJson(Map json)
: id = json['id'],
title = json['title'],
description = json['description'],
author = json['author'],
imageUrl = json['imageUrl']; Map toJson() => {
'title': title,
'descritpion': description,
};
}
http: ^0.12.0
最新文章
- Quartus II USB-Blaster驱动解决
- SAP HANA专题分析目录
- SQL Server :事务和锁
- 对编程语言的需求总结为四个:效率,灵活,抽象,生产率(C++玩的是前三个,Java和C#玩的是后两个)
- poj1050(nyoj104 zoj1074)dp问题
- IOS开发之UIView的基本使用
- JDBC调用存储过程的例子
- install atom markdown preview plus error
- Zeroc Ice开发环境搭建
- 系统设计Design For Failure思想
- Python列表中查找某个元素的索引(多个)
- Windows Vue 安装
- ios uibutton加数字角标
- 经常在比特币中看到的merkle树是什么?
- Web接口测试-HttpClient
- vue框架(三)_vue引入jquery、bootstrap
- C#正则表达式 - 精通版
- 手把手教你开发jquery插件(三)
- android异常:Can not perform this action after onSaveInstanc
- 【算法】2-sat问题【模板】