pubspec.yaml

1
2
dependencies:
  http: 0.11.3+16

main.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import 'dart:async';
import 'dart:convert';

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget{
  MyAppState createState()=>  MyAppState();
}

class MyAppState extends State<MyApp> {
  String _txt = "Nothing";

  void handleTimeout() {
    loadData().then((_post) {
      print("===${_post.title}");
      setState(() {
        _txt = _post.title;
      });
    });
  }

  @override
  void initState() {
    super.initState();
   
    // 2초 후에 데이터 로드
    Timer(Duration(seconds: 2), handleTimeout);
  }

  @override
  Widget build(BuildContext context){
    return MaterialApp(
      home: Text(_txt)
    );
  }
}

Future<Post> loadData() 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'],
    );
  }
}

JSON 데이터

1
2
3
4
5
6
7
// https://jsonplaceholder.typicode.com/posts/1
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}