[Flutter]/[Flutter]
[Flutter] BuildContext와 Theme - 스타일시트 저장하기
노트포미
2024. 7. 22. 21:26
[ BuildContext context 간단 정리 ]
: context는 위젯 트리에서 해당 위치의 위치 정보와 부모 요소들의 모든 정보를 담고 있다
-> 부모의 데이터에 접근할 수 있게 해준다. (A handle to the location of a widget in the widget tree)
즉, widget tree에 가장 마지막 자식인 Text(My Large Title)에서 부모인 MaterialApp의 데이터에 접근 할 수 있게 해준다
* MyLargeTitle이라는 분리된 Class로 정의되어 있더라도, 정보를 가져옴.
[ Theme - 스타일시트 저장 ]
: flutter에서는 위젯의 스타일을 한 곳에 저장할 수 있는 기능을 제공한다.
-> color, style등을 모두 저장해 둘 수 있음
<사용법>
//선언 방법
MaterialApp(
theme: ThemeData(
textTheme: TextTheme(
headlineLarge: TextStyle(
color: Colors.red,
),
),
),
//코드 생략
}
//적용 방법
color: Theme.of(context).textTheme.headlineLarge?.color,
*flutter의 null-safety기능으로 null이 되지 않게 하기 위해서 ?나 !를 작성한다
- ? : "null이 아니라면~ "
- ! : "nul 아님!!!!!"
[문제]
: 분리된 MyLargeTitle위젯에서 theme을 사용하는 방법으로 이미지처럼 만들기
[정답]
import 'package:flutter/material.dart';
void main() {
runApp(const App());
}
//widget
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
//데이터를 저장하고, state를 확인해서 UI를 변형하는 클래스
class _AppState extends State<App> {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData( //MaterialApp에 저장된 theme성질
textTheme: const TextTheme(
headlineLarge: TextStyle(
color: Colors.red,
),
),
),
home: const Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
MyLargeTitle(), //MyLargeTitle()로 분리된 클래스 위젯
],
),
),
));
}
}
class MyLargeTitle extends StatelessWidget {
const MyLargeTitle({
super.key,
});
@override
Widget build(BuildContext context) {
return Text(
'My Large Title',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
//context를 통해 부모(MaterialApp)의 성질인 theme에 접근
color: Theme.of(context).textTheme.headlineLarge?.color,
),
);
}
}