log
First I need to know how to type the flutter log. Search the flutter log and get the answer — print()/debugPrint()
You can also use another package
import 'dart:developer';
log('data: $data');
Copy the code
Request network
Then search for flutter make HTTP request to find flutter documents about HTTP
Flutter. Dev/docs/cookbo…
- Install dependencies, then flutter Packages get
- import ‘package:http/http.dart’ as http;
And then the core logic goes something like this
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'); }}Copy the code
Looks a lot like TypeScript code.
Call time
So when do YOU call fetchPost?
The documentation says it is not recommended to call it in a build.
Also, we don’t normally call axios in React render.
One approach recommended by the documentation is to initiate the request in the initState or didChangeDependencies lifecycle function of the StatefulWidget.
class _MyAppState extends State<MyApp> {
Future<Post> post;
@override
void initState() {
super.initState(); post = fetchPost(); }...Copy the code
Another approach is to request and then pass the Future instance to a StatelessWidget
How do I present data with FutureBuilder
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
returnCircularProgressIndicator(); });Copy the code
FutureBuilder accepts a Future and a Builder, and Builder renders different parts based on the contents of snapshot.
The complete code
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// How is data requested
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'); }}/ / modeling
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']); }}// Make the request at the beginning
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 is handy here
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title); // Get the title and display it
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
/ / load
returnCircularProgressIndicator(); },),),),); }}Copy the code
Only FutureBuilder seems to need special attention.
In the next section I will request custom data on LeanCloud and try rendering in the list.
To be continued…