RN에서 가장 주요 개념이었던 state를 flutter에서도 사용해보았다.
기존 StatelessWidget => StatefulWidget으로 변경해야 한다.
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// 기존 UI
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
....
}
}
State를 extends하는 _MyAppState에는 기존 UI & state 데이터를 가진다.
예제로 버튼을 누르면 count 변수의 값을 증가시키는 코드를 작성하였다.
class _MyAppState extends State<MyApp> {
void onClicked() {
setState(() {
counter += 1;
// setState 함수 호출 -> build 메소드 재실행
// (새로운 데이터가 있어 -> flutter UI 새로고침)
});
}
int counter = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
Sate 클래스 안에 count 변수를 작성한다.
버튼을 누를 때 실행되는 메소드 onClicked()는
count 를 1 증가 -> 새로운 데이터를 UI에 업데이트 하는 동작을 수행한다.
새로운 데이터가 있음을 flutter에게 알려주고 -> flutter는 build 매소드를 재실행 -> UI가 업데이트 된다 (화면 상의 count 숫자가 1 증가)
기억해야 하는 setState의 특징
void onClicked(){
counter += 1;
setState((){})
}
이렇게 하더라도 counter로 변수가 변경되고 -> setState로 UI가 업데이트 된다