Flutter

dart HTTP 요청과 응답 처리 및 파싱

whs5758 2025. 8. 19. 17:12
android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET"/>
import 'package:flutter/material.dart'; // 모바일로 인식 하려면 선언
import 'package:http/http.dart' as http;

void main() async {
  fetchTodoList();
}

// https://jsonplaceholder.typicode.com/todos/1
// Future (응답, 에러)

Future<http.Response> fetchTodo() async {
  const String url = "http://jsonplaceholder.typicode.com/todos/10";
  http.Response response = await http.get(Uri.parse(url));
  print(' ->>>>>   response : ${response}  <<<<--');
  return response;
}

// http://jsonplaceholder.typicode.com/todos
Future<http.Response> fetchTodoList() async {
  const url = "http://jsonplaceholder.typicode.com/todos/1";
  http.Response response = await http.get(Uri.parse(url));
  print(' 출력1 :  ${response.statusCode}');
  print(' 출력2 :  ${response.headers}');
  print(' 출력3 :  ${response.body}');
  return response;
}
import 'package:flutter/material.dart';
import 'home_page.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}
import 'package:flutter/material.dart';

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

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

class _HomePageState extends State<HomePage> {
  // 화면 구성 -- button() --> API 응답 받아서 화면에 정보를 뿌려 주세요.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [],
      ),
    );
  }
}

 

중첩된 구조 파싱 처리

class User {
  final int? id;
  final String? name;
  final String? username;
  final String? email;
  final Address? address;
  final String? phone;
  final String? website;
  final Company? company;

  User({
    this.id,
    this.name,
    this.username,
    this.email,
    this.address,
    this.phone,
    this.website,
    this.company,
  });

  User.fromJson(Map<String, dynamic> json)
      : id = json['id'] as int?,
        name = json['name'] as String?,
        username = json['username'] as String?,
        email = json['email'] as String?,
        address = json['address'] != null
            ? Address.fromJson(json['address'] as Map<String, dynamic>)
            : null,
        phone = json['phone'] as String?,
        website = json['website'] as String?,
        company = json['company'] != null
            ? Company.fromJson(json['company'] as Map<String, dynamic>)
            : null;
}

class Address {
  final String? street;
  final String? suite;
  final String? city;
  final String? zipcode;
  final Geo? geo;

  Address({
    this.street,
    this.suite,
    this.city,
    this.zipcode,
    this.geo,
  });

  Address.fromJson(Map<String, dynamic> json)
      : street = json['street'] as String?,
        suite = json['suite'] as String?,
        city = json['city'] as String?,
        zipcode = json['zipcode'] as String?,
        geo = json['geo'] != null
            ? Geo.fromJson(json['geo'] as Map<String, dynamic>)
            : null;
}

class Geo {
  final String? lat;
  final String? lng;

  Geo({
    this.lat,
    this.lng,
  });

  Geo.fromJson(Map<String, dynamic> json)
      : lat = json['lat'] as String?,
        lng = json['lng'] as String?;
}

class Company {
  final String? name;
  final String? catchPhrase;
  final String? bs;

  Company({
    this.name,
    this.catchPhrase,
    this.bs,
  });

  Company.fromJson(Map<String, dynamic> json)
      : name = json['name'] as String?,
        catchPhrase = json['catchPhrase'] as String?,
        bs = json['bs'] as String?;
}