flutter

[Flutter] ThemeData

킹왕짱지지 2024. 3. 28. 15:59

1. ThemeData

- themeData는 밖으로 다른 파일로 뺄 수도 있음! 

- 모든 것들에 스타일이 동일하게 적용된다는 장점

- 가까운 것부터 적용되므로 appbar의 action icon을 지정했다면 그거는 appbartheme으로 따로 적용해줘야함! 

- 레이아웃이 훨씬 깔끔해 보인다! 

void main() {
  runApp(MaterialApp(
      theme: ThemeData(
        iconTheme: IconThemeData(color : Colors.black),
        appBarTheme: AppBarTheme(
            color : Colors.white,
        actionsIconTheme:IconThemeData(color: Colors.black) )
      ),
      home: MyApp()));

 

Text 위젯 스타일

Text() : bodyText2

ListTile() : subtitle1

TextButton() : button

AppBar() : headline6

 

--> 근데 그냥 외우지 말고 변수로 출약해서 쓰는게 낫다!! 

 

var text1 = TextStyle(color : Colors.red);
Text('글자', style : text1)

 

Button 위젯 스타일 

textButtonTheme: TextButtonThemeData(
      style: TextButton.styleFrom(
        backgroundColor: Colors.grey,

      )

 

bottomNavigationBarTheme

  bottomNavigationBarTheme: BottomNavigationBarThemeData(
    backgroundColor: Colors.white,
    elevation: 2,
    selectedItemColor: Colors.black,
    unselectedItemColor: Colors.grey,

 

2. ThemeData 다른 파일로 분리 

lib/style.dart 파일 생성

기본 material 패키지 import 하고 변수로 themeData 받기

import 'package:flutter/material.dart';

var theme = ThemeData(
    iconTheme: IconThemeData(color : Colors.black),
    appBarTheme: AppBarTheme(
        color : Colors.white,
        elevation: 1,
        titleTextStyle: TextStyle(color:Colors.black, fontSize:25),
        actionsIconTheme:IconThemeData(color: Colors.black) )
);

 

다시 main.dart로 돌아와서

style파일 import하고 theme에 변수명 가져오기

import 'package:flutter/material.dart';
import './style.dart';

void main() {
  runApp(MaterialApp(
      theme: theme,
      home: MyApp()));
}

 

* 주의 import 한 파일이 있다면 변수 중복 문제 피해야함! 

solution 1)  as style로 설정해주기 !!

import 'package:flutter/material.dart';
import './style.dart' as style;

void main() {
  runApp(MaterialApp(
      theme: style.theme,
      home: MyApp()));
}

 

solution 2)  언더바 활용하기 !! (_변수명 _함수명 _클래스명)

var _var1; 이런식으로 하면 다른 파일에선 쓸 수 없는 이 파일내에서 쓰는 함수가 됨 .

실수로 다른 파일에서 갖다쓰는 거 방지 가능

 

3. 레이아웃 중간에 ThemeData() 생성 방법

Container( 
  child : Theme(
    data : ThemeData(글자 파랗게 하는 스타일~~),
    child : Container(
      여기부터는 글자 파래짐~~
    )
  )
)

 

4. ThemeData() 안의 특정 스타일 불러오기

Text('안녕', style: Theme.of(context).textTheme.bodyText1)