[Flutter] StatelessWidget()

Tyger·2021년 10월 18일
0

StatelessWidget()

앞서 작성했던 StatefulWidget에 이어서 StatelessWidget에 대하여 알아보도록 하겠다

StatelessWidget에서 state 변경 방법은 다음 글을 참고하세요

StatelessWidget은 말 뜻 그대로 상태가 없는 위젯을 말한다
상태가 없다는 것은 StatefulWidget처럼 상태를 변경할 수 없다는 것으로 StatelessWidget의 기본 소스 코드를 보면 createState 부분이 없다는 것을 알 수 있다

StatelessWidget은 StatefulWidget 보다 처음에는 사용하기 어려울 수 있지만 개발을 좀 더 해보다 보면 매우 가볍게 사용 할 수 있는 위젯이다

아래의 소스 코드를 실행 해보면 아무런 event가 발생하지 않아 상태가 변경이 안되는 것을 확인할 수 있음

StatelessWidget()에 대한 추가적인 상태관리는 다음 글에서 계속 이어가겠다

import 'package:flutter/material.dart';

class VelogWidgetStateless extends StatelessWidget {
  const VelogWidgetStateless({Key? key}) : super(key: key);
  
  Widget build(BuildContext context) {
    int count = 0;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: const Text('Stateless'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Padding(
            padding: const EdgeInsets.only(bottom: 30),
            child: Text(
              count.toString(),
              style: const TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              buttonForm(
                  context: context,
                  title: '+',
                  onTap: () {
                    count++;
                  }),
              buttonForm(
                  context: context,
                  title: '-',
                  onTap: () {
                    count--;
                  }),
              buttonForm(
                  context: context,
                  title: 'RESET',
                  onTap: () {
                    count = 0;
                  }),
            ],
          ),
        ],
      ),
    );
  }

  Container buttonForm({
    required BuildContext context,
    required String title,
    required Function() onTap,
  }) {
    return Container(
      width: MediaQuery.of(context).size.width * 0.25,
      height: MediaQuery.of(context).size.height * 0.07,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(18), color: Colors.deepOrange),
      child: InkWell(
        onTap: onTap,
        child: Center(
            child: Text(
          title,
          style: const TextStyle(
              fontSize: 25, fontWeight: FontWeight.bold, color: Colors.white),
        )),
      ),
    );
  }
}
profile
Flutter Developer

0개의 댓글