본 문서는 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.'));
}

Comment and share

크리에이티브 커먼즈 라이선스
이 저작물은 크리에이티브 커먼즈 저작자표시-비영리-변경금지 2.0 대한민국 라이선스에 따라 이용할 수 있습니다.

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

Basic Dogs App Setup ( 기본 강아지 앱 설정)

이것은 굉장한 프레임워크다.

이 기본 앱 튜토리얼에서는 2012년 We Rate Dogs vs Brant 대결을 통해 역대 최고의 Twitter대화에서 영감을 받아 매우 간단하고 순수한 플러터 앱을 만들 것이다. (역자주: 2010년 트위터의 WeRateDogs라는 계정이 애완견 사진을 올리고 사용자들끼리 평가와 대화를 하는 트윗에 Brant라는 계정이 딴지를 걸기 시작한 사건으로 제가 확인은 안해봤지만 단일 대화 주제로는 트위터 설립이래 최고의 대화가 오갔다고 함.)

여기서 우리는 추가 package를 가져오지(사용하지) 않을 것이며 아키텍쳐나 state관리에 대해 생각하지 않을 것이다.

이 작업이 끝날 때쯤이면, 플러터가 우리에게 얼마나 많은 것을 주었는지에 대해 상당히 놀랄것이다. 그리고 우리는 거의 모든 것을 커버하지 않을 것이다.(역자주: 플러터가 제공하는 수 많은 기능에 대해 다루진 않겠다는 의미 인듯.)

우리가 무엇을 만들지 보자.
dogs1 dogs2

완성된 코드 링크

우리는 새로운 앱에서 시작할 것이다. 일단 플러터 설치 및 설정을 하고 난 후 (설치 및 설정 되어 있다면 pass) 새로운 앱을 만든다.

1
2
3
flutter create basic_flutter_app
cd basic_flutter_app
flutter run

또는 Github에서 이미 생성된 app을 clone받아도 된다.

1
2
3
4
git clone https://github.com/ericwindmill/flutter_by_example_apps.git
cd flutter_by_example_apps/blank_flutter_app
flutter packages get
flutter run

이것은 새롭고, 빈(?) 플러터 앱을 제공한다.

Comment and share

크리에이티브 커먼즈 라이선스
이 저작물은 크리에이티브 커먼즈 저작자표시-비영리-변경금지 2.0 대한민국 라이선스에 따라 이용할 수 있습니다.
  • page 1 of 1
Author's picture

Jace Shim


Seoul, Korea