본문 바로가기

Flutter (with 코딩셰프)

[2023.12.08] 플러터(flutter) 조금 매운맛 강좌 02 | Sateful Widget #2

<< 소스 코드 >>

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

//stateless widget이라서 화면에 counter가 올라가지 않음
//ctrl + s 눌러 저장 시 변경된 counter 값이 화면에 반영됨.
class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAppState();
  }
}

class MyAppState extends State<MyApp>{

  int counter = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              //화면에 문구와 counter 변수값 출력
              Text('You have pushed the button this many times:'),
              //Text Widget은 Stateless Widget이라서 글자가 바뀌지 않음.
              Text(
                  '$counter',
                style: Theme.of(context).textTheme.displayLarge,
              ),
              Checkbox(value: false, onChanged: (bool? value){})
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          //버튼 클릭 시 counter 변수 값. 증가
          onPressed: (){
            //State를 변경하려면 Build 메소드가 호출되어야함.
            //그래서 setState 함수로 Build 메소드를 호출함.
            setState(() {
              counter++;
              print("$counter");
            });
          },
        ),
      ),
    );
  }
}

 

<< 출력 화면 >>