변하지 않는 상태의 위젯을 말한다. 그런데 만약, 화면이 변할때 State한 요소에 변화를 주고 싶다면 StatefulWidget을 사용해야 한다.
stful이라고 입력하면 자동으로 위젯을 생성하기 위한 두가지 클래스가 생성이 된다.
작성방식은 같으며, main에서 호출할 HelloPage에 생성자로 들어갈 title을 final로 생성하고, 이를 넣는 생성자를 설정하면 된다.
final String title;
HelloPage(this.title);
main과 동일하게 createState()가 불려지면서 build를 호출한다.
이 build 내부에 요소들을 작성하면 Stateful한 위젯을 만들 수 있다.
구조는 앞에서 작성했던 구조와 동일하게 만들었다.(Scaffold, AppBar..)
📌StatefulWidget - 상태를 가질 수 있다.
class _HelloPageState extends State<HelloPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(onPressed : () {
print("잘 눌리나");
}),
appBar: AppBar(
title: Text(widget.title),
),
body: Text(widget.title, style: TextStyle(fontSize: 30)));
}
}
버튼 생성은 floatingActionButton 위젯을 사용한다. 특이한 점은 onPressed의 사용법이었는데, 이는 람다합수처럼 바뀐 표현법으로 사용이 가능하다.
class _HelloPageState extends State<HelloPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(onPressed : () =>
print("잘 눌리나")
),
appBar: AppBar(
title: Text(widget.title),
),
body: Text(widget.title, style: TextStyle(fontSize: 30)));
}
}
기존의 람다 함수는 ->로 정의했었는데 여기서는 => 라서 두줄이다..특이하네
이제 상태 변화를 체크할 수 있는 Action Button을 추가해준다.
return Scaffold(
floatingActionButton:
FloatingActionButton(
child : Icon(Icons.add),
onPressed : () =>
print("잘 눌리나")
),
appBar: AppBar(
title: Text(widget.title),
),
body: Text(widget.title, style: TextStyle(fontSize: 30)));
}
FloatingActionButton 위젯을 넣어주면 된다. 버튼을 정의하기 위해 내부에 child 속성을 정의하였다.
child 속성
위젯의 하위 요소나 내용을 나타내는데 사용된다. 일반적으로 다른 위젯을 포함한다. 즉, child는 주어진 위젯의 자식 위젯을 참조한다.
class HelloPage extends StatefulWidget {
// const HelloPage({super.key});
final String title;
HelloPage(this.title);
@override
State<HelloPage> createState() => _HelloPageState();
}
class _HelloPageState extends State<HelloPage> {
String _message = "Hello world"; //_ : private
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton:
FloatingActionButton(
child : Icon(Icons.add),
onPressed : _changeMessage),
appBar: AppBar(
title: Text(widget.title),
),
body: Text(_message, style: TextStyle(fontSize: 30)));
}
void _changeMessage() {
setState(() { //호출하면 ui를 변경
_message = "헬로 월드";
});
}
}
onPressed에 직접 요소를 정의하는 것이 아닌, method를 불러올 수 있도록 구성하였다.
불러온 method 안에 있는 setState()는, onPressed에서 이 메소드가 호출될 시, 요소를 변경시키는 기능을 한다.
⭐ message 필드의 앞에 붙은 _는 private 속성임을 나타낸다!
버튼을 눌러서 body의 message 부분을 바꾼것을 볼 수 있다.