Flutter 高效自學筆記(三)——網絡請求

log

首先我要知道如何打 log,搜一下 flutter log 就獲得了答案——print() / debugPrint()ios

也能夠使用另外一個包json

import 'dart:developer';
log('data: $data');
複製代碼

請求網絡

而後搜索 flutter make http request,就搜索到 Flutter 關於 http 的文檔axios

flutter.dev/docs/cookbo…網絡

  1. 安裝依賴,而後 flutter packages get
  2. import 'package:http/http.dart' as http;

而後核心邏輯大概是這樣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 展現數據

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 上的自定義數據,而且嘗試渲染在列表裏。

未完待續……

相關文章
相關標籤/搜索