본문 바로가기
Flutter

[flutter21] dio

by JINJINC 2025. 1. 14.
728x90
반응형

https://pub.dev/packages?q=dio&sort=like

 

Search results for dio

Pub is the package manager for the Dart programming language, containing reusable libraries & packages for Flutter and general Dart programs.

pub.dev

 

 

 

flutter에서 httpClient 통신을 사용하기 위해서는 라이브러리를 다운받아야 한다.

 

 

cmd 화면에서 설치 명령어를 넣거나, pubspec.yaml 파일에 depencey를 추가한 후 , pub get해준다.

 

 

Dio 객체 생성하는 방법
  //통신을 담당하는 클라이언트 객체를 가져오자
  Dio _dio = Dio();

 

 

테스트용 사이트

https://jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake and reliable API for testing and prototyping. Powered by JSON Server + LowDB. Serving ~3 billion requests each month.

jsonplaceholder.typicode.com

 

 

시나리오 코드 1 - Json을 get 받아오는 방법

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
          body: HomePage(),
        ),
      ),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //통신을 담당하는 클라이언트 객체를 가져오자
  Dio _dio = Dio();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _fetchTodos();
    //객체 실행시 한번 호출하는 메서드
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  //통신을 담당하는 메서드를 만들어 보자
  _fetchTodos() async {
    String path = 'https://jsonplaceholder.typicode.com/todos/1';

    //통신을 담당하는 코드는 기본적으로 예외처리 해줘야 한다.
    try {
      Response respone = await _dio.get(path);

      print('HTTP status code  : ${respone.statusCode}');
      print('서버 측에서 전달한 데이터 : ${respone.data}');
      print('HTTP data runtimeType  : ${respone.data.runtimeType}');

      // Map 타입  -> 값 호출방법
      print('----------------------------------');
      print('데이터-> title 값 확인 :  ${respone.data['title']}');
      print('데이터-> id 값 확인 :  ${respone.data['id']}');
      print('데이터-> userId 값 확인 :  ${respone.data['userId']}');
      print('데이터-> completed 값 확인 :  ${respone.data['completed']}');
    } catch (err) {
      print('실행시점의 예외');
      print(err.toString());
    }
  }
}

 

 

시나리오 코드 2 - Json을  객체에 담아보기 

 

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
          body: HomePage(),
        ),
      ),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //통신을 담당하는 클라이언트 객체를 가져오자
  Dio _dio = Dio();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _fetchTodos();
    //객체 실행시 한번 호출하는 메서드
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  //통신을 담당하는 메서드를 만들어 보자
  _fetchTodos() async {
    String path = 'https://jsonplaceholder.typicode.com/todos/1';

    //통신을 담당하는 코드는 기본적으로 예외처리 해줘야 한다.
    try {
      Response respone = await _dio.get(path);
      Map<String, dynamic> result = respone.data;

      ToDo todo = ToDo(
          userId: result['userId'],
          id: result['id'],
          title: result['title'],
          completed: result['completed']);

      print('결과 : ${todo.toString()}');
    } catch (err) {
      print('실행시점의 예외');
      print(err.toString());
    }
  }
}

class ToDo {
  int? userId;
  int? id;
  String? title;
  bool? completed;

  ToDo(
      {required this.userId,
      required this.id,
      required this.title,
      required this.completed});

  @override
  String toString() {
    return 'ToDo{userId: $userId, id: $id, title: $title, completed: $completed}';
  }
}

 

 

시나리오 코드 3- Json을  객체에서 파싱하는 방법

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
          body: HomePage(),
        ),
      ),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //통신을 담당하는 클라이언트 객체를 가져오자
  Dio _dio = Dio();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _fetchTodos();
    //객체 실행시 한번 호출하는 메서드
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  //통신을 담당하는 메서드를 만들어 보자
  _fetchTodos() async {
    String path = 'https://jsonplaceholder.typicode.com/todos/1';

    //통신을 담당하는 코드는 기본적으로 예외처리 해줘야 한다.
    try {
      Response respone = await _dio.get(path);
      ToDo todo1 = ToDo.fromJson(result);

    } catch (err) {
      print('실행시점의 예외');
      print(err.toString());
    }
  }
}

class ToDo {
  int? userId;
  int? id;
  String? title;
  bool? completed;

  ToDo(
      {required this.userId,
      required this.id,
      required this.title,
      required this.completed});
  //명명된 생성자
  ToDo.fromJson(Map<String, dynamic> json)
      : userId = json['userId'],
        id = json['id'],
        title = json['title'],
        completed = json['completed'];

  @override
  String toString() {
    return 'ToDo{userId: $userId, id: $id, title: $title, completed: $completed}';
  }
}

 

 

시나리오 코드 4- Json을 받은 객체를 위젯에 띄어보기 

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
          body: HomePage(),
        ),
      ),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //통신을 담당하는 클라이언트 객체를 가져오자
  Dio _dio = Dio();
  //모델링한 타입 추가 => 실패했을때를 대비하여 ? 옵셔널로 선언
  ToDo? _todo;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _fetchTodos();
    //객체 실행시 한번 호출하는 메서드
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: _todo == null
          ? CircularProgressIndicator() // 로딩 데이터
          : Column(
              children: [
                Text('Id: ${_todo!.id}'),
                Text('userId: ${_todo!.userId}'),
                Text('title: ${_todo!.title}'),
                Text('completed: ${_todo!.completed}'),
              ],
            ),
    );
  }

  //통신을 담당하는 메서드를 만들어 보자
  _fetchTodos() async {
    String path = 'https://jsonplaceholder.typicode.com/todos/1';

    //통신을 담당하는 코드는 기본적으로 예외처리 해줘야 한다.
    try {
      Response respone = await _dio.get(path);
      setState(() {
        _todo = ToDo.fromJson(result);
      });
    } catch (err) {
      print('실행시점의 예외');
      print(err.toString());
    }
  }
}

class ToDo {
  int? userId;
  int? id;
  String? title;
  bool? completed;

  ToDo(
      {required this.userId,
      required this.id,
      required this.title,
      required this.completed});
  //명명된 생성자
  ToDo.fromJson(Map<String, dynamic> json)
      : userId = json['userId'],
        id = json['id'],
        title = json['title'],
        completed = json['completed'];

  @override
  String toString() {
    return 'ToDo{userId: $userId, id: $id, title: $title, completed: $completed}';
  }
}

 

setState 해줘야 화면에 제대로 반영됨 

 

 

728x90
반응형

댓글