버튼으로 데이터 다시 불러오기
Coddy Flutter 여정의 데이터와 네트워크 섹션에 포함된 레슨. 27개 중 8번째.
새 데이터를 불러오려면 FutureBuilder에 새로운 future를 전달하세요. setState 안에서 만들면 화면이 다시 빌드되면서 새 future를 사용합니다:
IconButton(
icon: const Icon(Icons.refresh),
onPressed: () {
setState(() {
_tip = fetch('/tip');
});
},
)새 팁은 2초 후에 도착합니다. 데이터를 불러오는 동안에도 snapshot.hasData는 계속 true입니다. 빌더는 새 데이터가 이전 데이터를 대체할 때까지 이전 데이터를 유지합니다. hasData를 확인하면 이전 팁이 화면에 그대로 남고 앱이 작업 중이라는 표시가 나타나지 않습니다.
스피너를 다시 표시하려면 future가 현재 어떤 상태인지 나타내는 snapshot.connectionState를 확인하세요. future가 실행 중일 때는 ConnectionState.waiting이고, 실행이 끝나면 ConnectionState.done입니다:
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
return Text(snapshot.data!);실행이 끝나면 데이터가 있으므로 snapshot.data!를 안전하게 사용할 수 있습니다.
챌린지
중급다음 팁을 불러오는 새로고침 버튼을 추가하세요:
- 상단 바의
actions에Icons.refresh를 사용하는IconButton - 버튼을 누르면
setState에서_tip을 새로운fetch('/tip')으로 설정합니다 - 새 팁을 불러오는 동안 스피너가 표시됩니다.
snapshot.connectionState를 확인하세요
직접 해보기
import 'package:flutter/material.dart';
import 'api.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: TipScreen(),
);
}
}
class TipScreen extends StatefulWidget {
const TipScreen({super.key});
@override
State<TipScreen> createState() => _TipScreenState();
}
class _TipScreenState extends State<TipScreen> {
late Future<String> _tip;
@override
void initState() {
super.initState();
_tip = fetch('/tip');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Tip of the Day'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: FutureBuilder<String>(
future: _tip,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
snapshot.data!,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 24),
);
}
return const CircularProgressIndicator();
},
),
),
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
데이터와 네트워크의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러