Flutter 커스텀 위젯

황인호·2022년 12월 20일
0

Flutter

Q. 레이아웃 위젯이 너무 길다면?
=> 커스텀 위젯으로 깔끔하게 축약 가능

위젯을 한단어로 축약하려면??

  1. stless
  2. class 작명
  3. return 옆에 축약할 레이아웃을 넣는다.

끝...

line1. 커스텀 위젯은 class 로 만든다(class 는 변수와 함수를 보관하는 보관함이다.)
line2. class 에 어떤 파라미터를 넣을건지 정의하는 부분이다
line3. @overried 는 내꺼먼저 적용하라는 뜻이다.
line4. class 안에 build 라는 함수 만드는 부분이다.

사실 변수나 함수 문법으로도 축약이 가능하다 그럼에도 잘쓰지 않는 이유는 성능상에 이슈가 있을수있어서이다.

그래서 변하지 않는 UI들은 변수 함수로 축약을해도 상관이없다.

ListView = 자동으로 반복해줌
itemCount = 얼마나 반복할건지??
itemBuilder = 위젯을 반복생성시켜줌

import 'package:flutter/material.dart';

void main() {
  // 앱을 구동시켜달라는 뜻
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({super.key});

  var a = 1;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        floatingActionButton: FloatingActionButton(
          child: Text(a.toString()),
          onPressed: () {
            print(a);
            a++;
          },
        ),
        appBar: AppBar(),
        body: ListView.builder(
          // 얼마나 반복할건지?
          itemCount: 100,
          // c = context
          // i = 위젯이 반복생성될때마다 +1 되는 정수
          itemBuilder: (c, i) {
            print(i);
            return HomeWorkWidget();
          },
        ),
        bottomNavigationBar: HomeWorkWidget2(),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [Icon(Icons.account_circle), Text('홍길동')],
        ),
        Row(
          children: [Icon(Icons.account_circle), Text('홍길동')],
        ),
        Row(
          children: [Icon(Icons.account_circle), Text('홍길동')],
        ),
      ],
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return BottomAppBar(
      child: SizedBox(
        height: 70,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Icon(Icons.phone),
            Icon(Icons.message),
            Icon(Icons.contact_page),
          ],
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: Text('안녕'),
    );
  }
}
profile
성장중인 백엔드 개발자!!

0개의 댓글