[flutter] 플러터 프로바이더를 이용한 로딩 화면 처리
앱을 개발하다 보면 데이터를 불러오거나 다양한 초기화 작업이 필요할 때가 있습니다. 이런 작업을 하는 동안 사용자에게 로딩 화면을 보여주는 것은 좋은 사용자 경험을 제공하는 데 도움이 됩니다. 플러터(Flutter) 앱에서는 프로바이더(Provider)를 이용하여 간단하게 로딩 화면을 처리할 수 있습니다.
프로바이더(Provider)란?
프로바이더는 플러터 앱에서 상태 관리를 쉽게 하기 위한 패키지입니다. 플러터 앱의 상태를 관리하고 상태 변화에 따라 위젯을 업데이트할 수 있도록 도와줍니다.
로딩 화면 처리하기
다음은 플러터에서 프로바이더를 이용하여 로딩 화면을 처리하는 간단한 예제입니다.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => LoadingProvider(),
child: MaterialApp(
home: LoadingScreen(),
),
);
}
}
class LoadingProvider with ChangeNotifier {
bool _isLoading = false;
bool get isLoading => _isLoading;
void setLoading(bool value) {
_isLoading = value;
notifyListeners();
}
}
class LoadingScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final loadingProvider = Provider.of<LoadingProvider>(context);
return loadingProvider.isLoading ? _buildLoadingScreen() : _buildMainScreen();
}
Widget _buildLoadingScreen() {
return Center(
child: CircularProgressIndicator(),
);
}
Widget _buildMainScreen() {
return Scaffold(
appBar: AppBar(
title: Text('로딩 화면 처리'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
final loadingProvider = Provider.of<LoadingProvider>(context, listen: false);
loadingProvider.setLoading(true);
// 데이터 불러오거나 초기화 작업 수행
// 작업 완료 후 setLoading(false) 호출
},
child: Text('로딩 시작'),
),
),
);
}
}
위의 예제는 프로바이더를 사용하여 로딩 화면을 처리하는 방법을 보여줍니다. LoadingProvider 클래스를 만들고 그 안에서 isLoading 변수를 사용하여 현재 로딩 상태를 관리하고 setLoading 메서드를 통해 로딩 상태를 변경한 후 화면을 업데이트합니다.
이렇게 프로바이더를 사용하여 로딩 화면을 처리하면 상태 관리를 효과적으로 할 수 있고, 사용자 경험을 향상시킬 수 있습니다.
참고 자료: