본 문서는 Fluter Example의 내용을 원저작자의 동의하에 번역한것 입니다.
원 저작자 Eric Windmill에게 감사를 전합니다.
이해하는데 불필요한 문장은 과감하게 버렸습니다. 오 번역에 대해서 의견 주시면 적극 반영 하겠습니다.

#Data Model & HTTP

1. Get to a Clean Slate

모든 플러터앱은 main.dart로 시작한다. Counter앱 관련한 부분을 제거하면 다음과 같다:

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
// main.dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
/// MaterialApp is the base Widget for your Flutter Application
/// Gives us access to routing, context, and meta info functionality.
return MaterialApp(
title: 'We Rate Dogs',
// Make all our text default to white
// and backgrounds default to dark
theme: ThemeData(brightness: Brightness.dark),
home: MyHomePage(title: 'We Rate Dogs'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
/// Scaffold is the base for a page.
/// It gives an AppBar for the top,
/// Space for the main body, bottom navigation, and more.
return Scaffold(
/// App bar has a ton of functionality, but for now lets
/// just give it a color and a title.
appBar: AppBar(
/// Access this widgets properties with 'widget'
title: Text(widget.title),
backgroundColor: Colors.black87,
),
/// Container is a convenience widget that lets us style it's
/// children. It doesn't take up any space itself, so it
/// can be used as a placeholder in your code.
body: Container(),
);
}
}

2. Dog Model 클래스 생성.

data model을 위해 Dog이라는 일반 Dart클래스를 만든다.

첫번째로 dog_model.dart라는 파일을 lib 폴더안에 생성한다.

1
2
3
- lib
-dog_model.dart
-main.dart

저 파일에서 몇 가지 속성을 가진 수퍼 기본 클래스 (super basic class)를 만들 것이다.

1
2
3
4
5
6
7
8
9
10
11
class Dog {
final String name;
final String location;
final String description;
String imageUrl;

// 모든 강아지는 10점부터 출발한다. 왜냐면 다 좋은 강아지니깐~
int rating = 10;

Dog(this.name, this.location, this.description);
}

3. 강아지 사진 얻기

우리는 강아지 이미지를 생성하기 위해 API키 또는 다른 어떠한것도 필요없는 매우 간단한 API를 사용할 것이다.
random하게 강아지 이미지를 찾아주는 dog.ceo를 이용할 것이다.

Dog클래스에 다음 메서드를 추가하자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// dog_model.dart

Future getImageUrl() async {
// Null check so our app isn't doing extra work.
// If there's already an image, we don't need to get one.
if (imageUrl != null) {
return;
}

// This is how http calls are done in flutter:
HttpClient http = HttpClient();
try {
// Use darts Uri builder
var uri = Uri.http('dog.ceo', '/api/breeds/image/random');
var request = await http.getUrl(uri);
var response = await request.close();
var responseBody = await response.transform(utf8.decoder).join();
// The dog.ceo API returns a JSON object with a property
// called 'message', which actually is the URL.
imageUrl = json.decode(responseBody)['message'];
} catch (exception) {
print(exception);
}
}

주의: 위 코드를 추가 하려면 두개의 Dart패키지를 import해야 함.

1
2
import 'dart:convert'; // json string 변환을 위함.
import 'dart:io'; // HttpClient를 위함.

4. new Dog class로 약간의 sample 데이터 생성.

main.dart에서 강아지 몇마리를 생성해 보자.

첫번째로 dog_model.dart를 import하자.

1
2
3
4
5
// main.dart

import 'package:flutter/material.dart';

import 'dog_model.dart';

그리고 약간의 강아지를 추가.

1
2
3
4
5
6
7
8
9
10
11
12
// main.dart in the State class

class _MyHomePageState extends State<MyHomePage> {
List<Dog> initialDoggos = []
..add(Dog('Ruby', 'Portland, OR, USA',
'Ruby is a very good girl. Yes: Fetch, loungin\'. No: Dogs who get on furniture.'))
..add(Dog('Rex', 'Seattle, WA, USA', 'Best in Show 1999'))
..add(Dog('Rod Stewart', 'Prague, CZ',
'Star good boy on international snooze team.'))
..add(Dog('Herbert', 'Dallas, TX, USA', 'A Very Good Boy'))
..add(Dog('Buddy', 'North Pole, Earth', 'Self proclaimed human lover.'));
}