정적인 화면 말고 동적인 화면 그리기 (StatefulWidget)

밥이·2022년 5월 12일
0
  • StatelessWidget은 build기반으로 화면을 그린다.
  • StatelessWidget는 상태가 없는 위젯. 상태값이 변해도 화면에 출력을 못함
  • StatefulWidget은 상태값이 변경되는 위젯을 쓸때 사용. (줄여서 stful 만듬)
  • StatefulWidget은 Class가 두개임. 첫번째는 받는부분, 두번째는 build부분에 실제 상태가 변경될 때 화면에 출력하는 부분(setState로 변경할 상태값 입력)
class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int count = 0;
  
@override
...생략...
body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        // crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ElevatedButton(
            onPressed: () {
              setState(() {
                count++;
              }); // 빌드가 다시 호출되서 리렌더링됨
              print('$count');
            },
            child: const Text('+'),
          ),
          Center(
            // width: MediaQuery.of(context).size.width,
            // width: double.maxFinite,
            child: Text('$count'),
          )
        ],
      ),
      

연습

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int count = 0;

@override
...생략...
body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          // crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                setState(() {
                  count++;
                });
              },
              child: const Text('+'),
            ),
            Text('$count'),
            // Center(
            //   child: Text('$count'),
            // )
          ],
        ),
      ),

0개의 댓글