[Flutter] 긴 코드 파일(변수)로 빼기

멋진감자·2025년 7월 15일
0

Flutter

목록 보기
10/25
post-thumbnail

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: MyApp(),
      theme: ThemeData(
        appBarTheme: AppBarTheme(
          elevation: 1,
          titleTextStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
        ),
      ),
      debugShowCheckedModeBanner: false,
    ),
  );
}

class MyApp extends StatelessWidget {
(생략)

여기서 ThemeData(~)를 잘라 lib 폴더 안에 새롭게 파일 하나를 만들고 붙인다.
만든 파일은 아무렇게나 작명 ex) style.dart

분리할 파일

에 옮긴 ThemeData(~)는 변수로 선언해주고
맨 끝에 세미콜론(;)을 붙인 뒤
main.dart에 있던 import 문을 갖다 붙인다.
기본 위젯들을 쓰기 위함이다.

import 'package:flutter/material.dart';

var theme = ThemeData(
  appBarTheme: AppBarTheme(
    elevation: 1,
    titleTextStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
  ),
);

마무리

정의한 변수명을 main.dart에서 ThemeData가 있던 곳에 작성하고,
해당 파일의 경로를 import 한다.
나는 자동완성 기능을 사용했는데
import 'style.dart';
import './style.dart';도 된다.

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

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

ThemeData() 뿐만 아니라
다른 모든 긴, 복잡한, 분리 필요한 코드도 요렇게 파일로 빼내어 관리할 수 있다.

import 시 변수 중복 문제 피하기

  1. as 키워드로 파일 재정의
import './style.dart as style';

(생략)
    MaterialApp(home: MyApp(), theme: style.theme),
  1. 한 파일 내에 여러 변수가 정의된 경우, 다른 파일에서의 사용 막기
    → 변수/함수/클래스명 앞에 언더바(_) 붙이기
    ex) var _byeonsoo = ..;
profile
난멋져

0개의 댓글