FutureBuilder 는 어떤것인가? 이 단어에서 유추해 보았을 때, 미래의 무언가를 쌓는다는건가? 라는 생각이 들었다.
FutureBuilder는 내가 유추한 것과 일치하지는 않지만, 비슷한 역할을 한다.주로, http 통신을 통해서 값을 받아오고, 그 값을 화면에 보여줄 때 사용하는 듯 하다.
http 통신을 통해서 jsonplaceholder 의 post 데이터를 받아왔다.
class Post {
int userId;
int id;
String title;
String body;
Post(this.userId, this.id, this.title, this.body);
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
json['userId'],
json['id'],
json['title'],
json['body'],
);
}
}
class Http {
Future<Post> getPost(String id) async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/$id');
final response = await http.get(url);
return Post.fromJson(jsonDecode(response.body));
}
}
Future<Post> _post = Http().getPost('1');
FutureBuilder<Post>(
future: _post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data?.title as String);
}
return const Text('로딩중');
},
),
많은 도움이 되었습니다, 감사합니다.