首先我要知道如何打 log,搜一下 flutter log 就获得了答案——print() / debugPrint()ios
也能够使用另外一个包json
import 'dart:developer';
log('data: $data');
复制代码
而后搜索 flutter make http request,就搜索到 Flutter 关于 http 的文档axios
而后核心逻辑大概是这样app
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
return Post.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load post');
}
}
复制代码
看起来很是像 TypeScript 代码。less
那么何时调用 fetchPost 呢?async
文档说不建议在 build 里调用。ide
也对,咱们通常也不在 React 的 render 里面调用 axios。函数
文档推荐的一种方法是在 StatefulWidget 的 initState 或 didChangeDependencies 生命周期函数里发起请求。post
class _MyAppState extends State<MyApp> {
Future<Post> post;
@override
void initState() {
super.initState();
post = fetchPost();
}
...
复制代码
另外一种方式就是先请求,而后把 Future 实例传给一个 StatelessWidget
FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
);
复制代码
FutureBuilder 接受一个 future 和 一个 builder,builder 会根据 snapshot 的内容,渲染不一样的部件。
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// 数据如何请求
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
return Post.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load post');
}
}
// 建模
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
// 一开始就发起请求
void main() => runApp(MyApp(post: fetchPost()));
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Post>( // 这里的 FutureBuilder 很方便
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title); // 获取 title 并展现
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// 加载中
return CircularProgressIndicator();
},
),
),
),
);
}
}
复制代码
看起来只有 FutureBuilder 须要特别关注一下。
下节我将请求 LeanCloud 上的自定义数据,而且尝试渲染在列表里。
未完待续……