https://flutter.dev/docs/cookbook/networking/background-parsing
isolate 는 thread 임..
1. http 패키지 추가
https://pub.dev/packages/http
디펜더시 추가하기
dependencies: http: ^0.12.2 |
라이브러리 임포트
import'package:http/http.dart'ashttp; |
사용법
1. 기본
<생략>
2. 요청을 여러번 할 때
var client = http.Client(); try { var uriResponse = await client.post('https://example.com/whatsit/create', body: {'name': 'doodle', 'color': 'blue'}); print(await client.get(uriResponse.bodyFields['uri'])); } finally { client.close(); } |
2. 네트워크요청
Future<http.Response> fetchPhotos(http.Client client) async {
return client.get('https://jsonplaceholder.typicode.com/photos');
}
url의(https://jsonplaceholder.typicode.com/photos)내용 중 일부.
{ "albumId": 1, "id": 1, "title": "accusamus beatae ad facilis cum similique qui sunt", "url": "https://via.placeholder.com/600/92c952", "thumbnailUrl": "https://via.placeholder.com/150/92c952" }, |
이것을 저장하기 위한 Photo클래스
class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
Photo({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
url: json['url'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
3. JSON을 List<Photo>로 컨버팅 하기
List<Photo> parsePhotos(String responseBody){
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();//cast는 빼도됨.
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get('https://jsonplaceholder.typicode.com/photos');
return parsePhotos(response.body);
}
4. isolate로 이동
compute() 는 spawn an isolate 함.
message 는 프리미티브 타입이거나 단순객체 이어야함. Futere 나 복잡한 개체는 안된다고함.
* 복잡한객체와 단순한 객체 차이점은 모르겟음
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get('https://jsonplaceholder.typicode.com/photos');
//return parsePhotos(response.body);
return compute(parsePhotos, response.body);
}
5. 전체 소스
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(primarySwatch: Colors.blue,
),
home:MyHomepage()
);
}
}
class MyHomepage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("My Home"),
),
body: FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot){
if(snapshot.hasError){
print(snapshot.error);
}
return snapshot.hasData
?PhotoList(photos:snapshot.data)
:Center(child: CircularProgressIndicator());
},
),
);
}
}
class PhotoList extends StatelessWidget{
final List<Photo> photos;
PhotoList({Key key, this.photos}) : super(key:key);
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2
),
itemCount: photos.length,
itemBuilder: (context, index){
return Image.network(photos[index].thumbnailUrl);
},
);
}
}
List<Photo> parsePhotos(String responseBody){
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();//cast는 빼도됨.
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get('https://jsonplaceholder.typicode.com/photos');
//return parsePhotos(response.body);
return compute(parsePhotos, response.body);
}
class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
Photo({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
url: json['url'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
'flutter' 카테고리의 다른 글
dart functor (0) | 2020.12.28 |
---|---|
flutter - firebase 로그인, 로그아웃 (0) | 2020.12.21 |
WidgetsBindingObserver (0) | 2020.12.08 |
Form, TextFormField (0) | 2020.12.04 |
데스트탑 플러터 (0) | 2020.11.11 |