HIT해

[Flutter] 상태를 변경하는 방법 본문

Flutter/Flutter 개발 노트

[Flutter] 상태를 변경하는 방법

힛해 2024. 1. 13. 15:35
728x90
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget { // 상태를 가질 수 없는 위젯
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: HelloPage('Helloo World') );
  }
}



// 상태를 변경하는 방법
// StatefulWidget을 만든 다음에
// 상속받은 State 안에다가 변경할 변숟ㄹ을 지정하고
// setState를 통해 변경해주면 된다
class HelloPage extends StatefulWidget { // 상태를 가질 수 있는 위젯의 기본 형ㅊ

  final String title;
  HelloPage(this.title);
  @override
  State<HelloPage> createState() => _HelloPageState();
}

class _HelloPageState extends State<HelloPage> {
  String _message = '안녕 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((){ // setState란 이 안에서 호출하면 UI를 변경하겠다.
      _message = '하이';
    });
  }
}

 

1. Stateful 위젯을 만든다

class HelloPage extends StatefulWidget { // 상태를 가질 수 있는 위젯의 기본 형ㅊ

  final String title;
  HelloPage(this.title);
  @override
  State<HelloPage> createState() => _HelloPageState();
}

 

2. 상속받은 State 안에 변경할 변수들을 지정

class _HelloPageState extends State<HelloPage> {
  String _message = '안녕 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)));
  }

 

3. 메서드에서 값을 바꿔준다.

void _changeMessage() {
    setState((){ // setState란 이 안에서 호출하면 UI를 변경하겠다.
      _message = '하이';
    });
  }