[flutter] 플러터에서 useState 훅(hook)을 이용한 상태 초기화와 업데이트
플러터(Flutter)에서 useState 훅을 사용하여 상태를 초기화하고 업데이트할 수 있습니다. 이를 통해 간편하게 상태를 관리하고 UI를 업데이트할 수 있습니다.
useState 훅이란?
useState 훅은 플러터에서 상태값을 유지하고 업데이트하기 위한 함수입니다. 이를 사용하면 클래스형 컴포넌트의 state와 유사한 기능을 함수형 컴포넌트에서 활용할 수 있습니다.
상태 초기화하기
아래는 useState 훅을 사용하여 상태를 초기화하는 예시입니다.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final countState = useState(0);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('useState 훅 예제'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'버튼을 눌러 상태를 업데이트하세요:',
),
Text(
'${countState.value}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
countState.value++;
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
),
);
}
}
위 예시에서 useState 훅을 사용하여 countState를 초기화하고, 버튼을 눌러 상태를 업데이트하는 방법을 확인할 수 있습니다.
상태 업데이트하기
아래는 useState 훅을 사용하여 상태를 업데이트하는 예시입니다.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final countState = useState(0);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('useState 훅 예제'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'버튼을 눌러 상태를 업데이트하세요:',
),
Text(
'${countState.value}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
countState.value++;
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
),
);
}
}
위 예시에서 countState의 value를 증가시키는 방법을 확인할 수 있습니다.
useState 훅을 이용하면 플러터 앱에서 상태를 초기화하고 업데이트하는 것이 간단해집니다. 함수형 컴포넌트를 활용하여 상태를 관리하고 UI를 업데이트할 수 있습니다.
더 많은 정보를 원하시면 공식 플러터 문서를 확인해보세요.