본문 바로가기
프로젝트/웹툰 앱 만들기

[웹툰 앱 만들기] Theme, init & dispose

by 두 그루 2023. 5. 6.

Theme

Theme을 이용하여 미리 설정해둔 값들을 사용할 수 있다. 예시로 UI에 사용할 특정 노란색, 폰트의 크기 등이 있다.

 

override한 build 함수에서 teme을 설정하고, build 함수의 context parameter를 이용하여 실제 사용하고자 하는 곳에 적용하면 된다. 아래 코드는 특정 Text의 크기와 색을 설정한 예시다.

 

class _ApptState extends State<App> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        textTheme: const TextTheme(
          titleMedium: TextStyle(
            color: Colors.green[300],
            fontSize: 40,
          ),
        ),
      ),
      home: Scaffold(
      	backgroundColor: const Color.fromARGB(255, 244, 208, 3),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const [
              myTitle(),
            ],
          ),
        ),
      ),
    );
  }
}

build 함수 안에서 theme을 설정한다.

 

class myTitle extends StatelessWidget {
  const myTitle({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Text(
      'This is my TITLE!',
      style: TextStyle(
        color: Theme.of(context).textTheme.titleMedium?.color,
        fontSize: Theme.of(context).textTheme.titleMedium?.fontSize,
      ),
    );
  }
}

그리고 적용하고자 하는 myTitle()은 context를 활용하여 style을 지정한다.

 

https://github.com/soaringwave/Flutter-studying/commit/0f149d48ab053eee8bde01399d0a8bc7cbff031f

 

Apply textTheme into myTitle widget · soaringwave/Flutter-studying@0f149d4

Showing 1 changed file with 11 additions and 4 deletions.

github.com

 

 

 

init & dispose

flutter에는 initState, dispose라는 특정함수가 있다. 두 함수는 필수로 사용해야 하는 것은 아니며, 각각의 용도가 있다.

 

initState()는 상태를 초기화할 때 사용한다. 예시로 이전 글에서 만들었던 counter처럼 counter는 처음에 빈 리스트를 가진다. 이런 처음 상태를 initState()에서 초기화하면 된다. 일반 변수를 class 안에서 선언 혹은 정의해도 되지만, initState()는 build 이전에 실행된다는 특징이 있다.

 

dispose()는 화면에서 요소가 사라질 때 실행된다. 예로 특정 버튼을 누르면 창이 닫길 때 실행하고자 사용할 수 있다.

 

아래 코드처럼 initState()와 dispose()를 사용할 수 있고, 밑의 동영상은 initState(), build(), dispose() 타이밍을 나타내고자 각각 출력하도록 했다.

class _MyTitleState extends State<MyTitle> {
  @override
  void initState() {
    super.initState();
    print("init");
  }

  @override
  void dispose() {
    super.dispose();
    print("dispose");
  }

  @override
  Widget build(BuildContext context) {
    print("build");
    // ...

 

 

 

https://github.com/soaringwave/Flutter-studying/commit/e6d364671a123a97769b06a666928f3b968ba500

 

Make toggle title to print dispose · soaringwave/Flutter-studying@e6d3646

Showing 1 changed file with 24 additions and 2 deletions.

github.com

 

댓글