study-note

dio

目次

基本構文

import 'package:dio/dio.dart';

void main() async {
  final dio = Dio(); // Dioインスタンスを作成

  try {
    final response = await dio.get('https://jsonplaceholder.typicode.com/todos/1');
    print(response.statusCode); // 200
    print(response.data);       // JSONがMap/Arrayとして返る
  } catch (e) {
    print('エラー: $e');
  }
}

リクエスト設定

タイムアウト/エラー処理

dio.options.connectTimeout = 5000; // 接続タイムアウト5秒
dio.options.receiveTimeout = 3000; // 受信タイムアウト3秒

try {
  final response = await dio.get('https://example.com/api');
} on DioError catch (e) {
  if (e.type == DioErrorType.connectTimeout) {
    print('接続タイムアウト');
  } else if (e.type == DioErrorType.receiveTimeout) {
    print('受信タイムアウト');
  } else {
    print('その他エラー: ${e.message}');
  }
}

Cookie/共通ヘッダー/インターセプター

dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) {
    print('リクエスト前: ${options.uri}');
    return handler.next(options);
  },
  onResponse: (response, handler) {
    print('レスポンス受信: ${response.statusCode}');
    return handler.next(response);
  },
));