點燈坊

戦わなければ、勝てない

http 呼叫 GET REST API

Sam Xiao's Avatar 2024-11-15

http 可呼叫 GET REST API 以 Future 形式回傳。

Version

Flutter 3.24

http

$ flutter pub add http
  • 安裝 http package

http 為 Dart 所提供的 package

Flutter

get01

  • Android 與 iOS 都成功以 GET 呼叫 REST API

GET

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Home extends StatefulWidget {
  const Home({super.key});

  
  State<Home> createState() => _Home();
}

class _Home extends State<Home> {
  var _title = '';

  Future<String> _fetchPost() async {
    final url = Uri.parse(
      'https://jsonplaceholder.typicode.com/posts/1',
    );

    try {
      final response = await http.get(url);

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        return data['title'];
      } else {
        if (kDebugMode) {
          print(response.statusCode);
        }
        return '';
      }
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
      return '';
    }
  }

  
  Widget build(BuildContext context) {
    var appBar = AppBar(
      title: const Text('http get'),
    );

    var floatingActionButton = FloatingActionButton(
      onPressed: () async {
        var title = await _fetchPost();
        setState(() => _title = title);
      },
      child: const Icon(Icons.add),
    );

    var body = Center(
      child: Text(_title),
    );

    return Scaffold(
      appBar: appBar,
      floatingActionButton: floatingActionButton,
      body: body,
    );
  }
}

Line 17

Future<String> _fetchPost() async {
}
  • _fetchPost():呼叫 GET REST API 回傳 Future,實務上會抽到 Service 內
  • 因為回傳 Future,所以為 async function

Line 18

final url = Uri.parse(      'https://jsonplaceholder.typicode.com/posts/1',
);
  • Uri.parse():將 url 轉成 Uri 物件

Line 23

final response = await http.get(url);
  • http.get():呼叫 GET REST API,因為 http.get() 回傳 Future,所以要使用 await

Line 25

if (response.statusCode == 200) {
  final data = jsonDecode(response.body);
  return data['title'];
}
  • 若回傳 statusCode 為 200,則從 response.body 取出資料
  • response.body 為 String,需使用 jsonDecoce() 將 String 轉成 Map

Line 29

if (kDebugMode) {
  print(response.statusCode);
}

return '';
  • kDebugMode:在 debug 模式印出 statusCode

Line 34

} catch (e) {
  if (kDebugMode) {
    print(e);
  }
  return '';
}
  • kDebugMode:在 debug 模式印出錯誤訊息

Line 49

onPressed: () async {
  var title = await _fetchPost();
  setState(() => _title = title);
},
  • onPressed():當 FloatingActionButton 按下時呼叫 _fetchPost(),並將回傳值存進 _title state

Line 56

var body = Center(
  child: Text(_title),
);
  • _title state 改變時,會自動更新 Text

Conclusion

  • 呼叫 GET REST API 為非同步行為,所以 http.get() 會回傳 Future,因此須以 async function 處理
  • 當呼叫 GET REST API 時,並不會直接更新 UI,而是將值存進 state,由 Flutter 自動更新 UI

Reference

pub.dev, http