flutter

flutter AppBar 파라미터 적용해서 사용하기

솨솨_ 2024. 1. 20. 16:55

동일한 폼에 appbar를 다른 페이지에서 사용해야 할 때 코드를 줄이기 위해 파라미터를 이용해 사용한다

 

를 만들어 줍니다. 단축어를 사용할 수 있다면 statelessW를 누르면 자동으로 생성됩니다.

import 'package:flutter/material.dart';

class TextPage extends StatelessWidget {
  final String title;  //제목
  final String minititle; // 옆 제목

  const TextPage({super.key, required this.title, required this.minititle});
//위 const에 required this.title , required this.minititle 추가

  @override
  Widget build(BuildContext context) {
    return PreferredSize( //사용하지 않아도 되지만 높이를 정하기 위해 사용하는 게 좋다
      preferredSize: const Size(0, 60), // Size(W,H)
      child: AppBar(
        titleSpacing: 0, // title 좌우 여백 없애기
        scrolledUnderElevation: 0.0, //appbar가 스크롤 될 때 바뀌는 컬러 없애기
        backgroundColor: Colors.white,
        leading: IconButton( // 왼쪽 컨텐츠
            icon: const Icon(Icons.arrow_back_rounded),
            style: IconButton.styleFrom(
              fixedSize: const Size(24, 24),
            ),
            padding: const EdgeInsets.all(0),
            onPressed: () => Navigator.pop(context)), // 뒤로가기
        title: ConstrainedBox( //어떤 이유에선지 centerTitle이 적용되지 않아서 감싼 것 적용이 잘 된다면 사용하지 않아도 된다.
          constraints:
              const BoxConstraints(maxHeight: 60, maxWidth: double.infinity), // 위와 동일한 이유
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                title,
                style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                    color: Color(0xff231815)),
              ),
              if (minititle != "") // 만약 소제목이 비어있지 않다면 아래 내용이 나타난다
                Padding(
                    padding: const EdgeInsets.only(left: 7),
                    child: Text(
                      minititle,
                      style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          color: Color(0xffFF7F67),
                          fontFamily: 'Rubik'),
                    ))
            ],
          ),
        ),
        centerTitle: true, // title 중앙으로
        actions: const [ // 오른쪽 컨텐츠
          IconButton(onPressed: null, icon: Icon(Icons.headset_rounded))
        ],
      ),
    );
  }

  Size get preferredSize => const Size.fromHeight(60); // PreferredSize로 감싸지 않았을 때 간혹 오류가 생기는데 이걸 쓰면 된다  
}