06. 기본 위젯 알아보기

2024. 4. 14. 11:37

06. 기본 위젯 알아보기

EveryThing is a Widget

  • 화면에서 보여지는 UI와 관련된 모든 요소는 위젯으로 구성되어 있음
  • 위젯의 종류
    • 자식(child)을 하나만 갖는 위젯
      • Container
      • GestureDetector
      • SizedBox
    • 다수의 자식(children)을 갖는 위젯
      • Column
      • Row
      • ListView

Child vs Children

  • child와 Children은 하위 위젯을 추가 할 때 사용함
//child

import 'package:flutter/material.dart';

void main() {
  runApp(
    const MaterialApp( //Material 기반의 위젯들을 사용할 수 있는 위젯
      home: Scaffold( // 화면 전체를 차지하며 레이아웃을 도와주고 UI 관련 특수 기능 제공
        body: Center(
          child: Text( 'Hello Code Factory',),
        ),
      ),
    ),
  );
}
//children

import 'package:flutter/material.dart';

void main() {
  runApp(
    const MaterialApp(
      debugShowCheckedModeBanner: false, // 디버그 배너 보이지 않게 함
      home: Scaffold(
        body: SizedBox(
          width: double.infinity,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center, // column일 때 세로축 기준 가운데 정렬

            children: [
              Text('Code'),
              Text('Factory'),
            ],
          )
        ),
      ),
    ),
  );
}

텍스트 관련 위젯

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text(
            '코드팩토리',
            style: TextStyle(
              fontSize: 16.0,              // 사이즈
              fontWeight: FontWeight.w700, // 굵기 
              color: Colors.blue,
            ),
          ),
        ),
      ),
    );
  }
}

제스처 관련 위젯 - 버튼

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: TextButton(
              onPressed: () {},
              style: TextButton.styleFrom(
                foregroundColor: Colors.red
              ),
              child: const Text('text button'),
          ),
        ),
      ),
    );
  }
}
//https://api.flutter.dev/flutter/material/TextButton-class.html

import 'package:flutter/material.dart';

void main() {
  runApp(TextButtonExampleApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('TextButton Sample')),
        body: const MyApp(),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              TextButton(
                onPressed: () {},
                style: TextButton.styleFrom(
                    foregroundColor: Colors.red
                ),
                child: const Text('text button'),
              ),

              const SizedBox(height: 30),

              OutlinedButton(
                  onPressed: () {},
                  style: OutlinedButton.styleFrom(
                    foregroundColor: Colors.red,
                  ),
                  child: const Text('Outlined Button')
              ),

              const SizedBox(height: 30),

              ElevatedButton(
                  onPressed: () {},
                  style: ElevatedButton.styleFrom(
                    foregroundColor: Colors.red,
                  ),
                  child: const Text('Elevated Button'),
              ),
            ],
          ),
      );
  }
}

제스처 관련 위젯 - 아이콘 버튼

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: IconButton(
             onPressed: () {},
             icon: const Icon(
               Icons.home,
             ),
          ),
        ),
      ),
    );
  }
}

제스처 관련 위젯 - GestureDetector

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: GestureDetector(
            onTap: () {
              print('on tap');
            },

            onDoubleTap: () {
              print('double tap');
            },

            onLongPress: () {
              print('Long Press');
            },

            child: Container(
              decoration: const BoxDecoration(
                color: Colors.red,
              ),
              width: 100.0,
              height: 100.0,
            ),
          ),
        ),
      ),
    );
  }
}

제스처 관련 위젯 - FloatingActionButton

import 'package:flutter/material.dart';

void main() {
  runApp(const FloatingActionButtonExample());
}

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


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: const Text('click'),
        ),
        body: Container(
          decoration: BoxDecoration(
            color: Colors.red,
            border: Border.all(
              width: 16.0,
              color: Colors.black,
            ),
            borderRadius: BorderRadius.circular(
              16.0
            ),
          ),
          height: 200.0,
          width: 100.0,
        ),
      ),
    );
  }

}

디자인 관련

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: SafeArea(
            top:true,
            bottom: true,
            left: true,
            right: true,
            child: Container(
              color: Colors.red,
              height: 300.0,
              width: 300.0,
            ),
          ),
        ),
      ),
    );
  }
}

배치 관련

//row

import 'package:flutter/material.dart';

class RowWidgetExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SizedBox(
          height: double.infinity,
          child: Row(
            // 주축 정렬 지정
            mainAxisAlignment: MainAxisAlignment.start,
            // 반대축 정렬 지정
            crossAxisAlignment: CrossAxisAlignment.center,
            // 넣고 싶은 위젯 입력
            children: [
              Container(
                height: 50.0,
                width: 50.0,
                color: Colors.red,
              ),
              // SizedBox는 일반적으로 공백을
              // 생성할 때 사용
              const SizedBox(width: 12.0),
              Container(
                height: 50.0,
                width: 50.0,
                color: Colors.green,
              ),
              const SizedBox(width: 12.0),
              Container(
                height: 50.0,
                width: 50.0,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  • MainAxisAlignment 정렬 방법 (가로 축 정렬과 관련된 것)
    • .start : 시작에 정렬
    • .center : 중앙에 정렬
    • .end : 끝에 정렬
    • .spaceBetween : 자식 위젯의 간격을 균등하게 정렬
    • .spaceAround : 자식 위젯의 간격을 균등하게 배정하고 왼쪽 끝과 오른쪽 끝을 위젯 사이 거리의 반만큼 배정해 정렬
    • .spaceEvenly : 자식 위젯의 간격을 균등하게 배치하고 왼쪽 끝과 오른쪽 끝도 균등하게 배치
  • crossAxisAlignment 옵션 (세로 축 정렬과 관련)
    • .start : 시작에 정렬
    • .center : 중앙에 정렬
    • .end : 끝에 정렬
    • .stretch : 늘려서 정렬
//Column


import 'package:flutter/material.dart';

class ColumnWidgetExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SizedBox(
          width: double.infinity,
          child: Column(
            // 주축 정렬 지정
            mainAxisAlignment: MainAxisAlignment.start,
            // 반대축 정렬 지정
            crossAxisAlignment: CrossAxisAlignment.start,
            // 넣고 싶은 위젯 입력
            children: [
              Container(
                height: 50.0,
                width: 50.0,
                color: Colors.red,
              ),
              // SizedBox는 일반적으로 공백을 생성할 때 사용
              const SizedBox(width: 12.0),
              Container(
                height: 50.0,
                width: 50.0,
                color: Colors.green,
              ),
              const SizedBox(width: 12.0),
              Container(
                height: 50.0,
                width: 50.0,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  • MainAxisAlignment 정렬 방법 (세로 축 정렬과 관련된 것)
    • .start : 시작에 정렬
    • .center : 중앙에 정렬
    • .end : 끝에 정렬
    • .spaceBetween : 자식 위젯의 간격을 균등하게 정렬
    • .spaceAround : 자식 위젯의 간격을 균등하게 배정하고 왼쪽 끝과 오른쪽 끝을 위젯 사이 거리의 반만큼 배정해 정렬
    • .spaceEvenly : 자식 위젯의 간격을 균등하게 배치하고 왼쪽 끝과 오른쪽 끝도 균등하게 배치
  • crossAxisAlignment 옵션 (가로 축 정렬과 관련)
    • .start : 시작에 정렬
    • .center : 중앙에 정렬
    • .end : 끝에 정렬
    • .stretch : 늘려서 정렬

+ Recent posts