ABOUT ME

늦은나이에 시작하는 성장스토리

Today
Yesterday
Total
  • [개발일지] flutter 앱개발 1주차
    Study/Development 2022. 8. 30. 21:12

     

    <스파르타코딩 flutter 강의 수강일지>

     

    1주차: Flutter 기본 이해 및 Dart 문법

    1. Flutter 이해하기

    Flutter를 이용하여, Widget Tree의 형태로 Widget으로 조립하여 앱 개발을 할 수 있다. 

     

    아래의 Widget catalog에서 원하는 위젯을 찾은 뒤, 작성한 Widget의 상위에 혹은 하위에 붙여넣어 앱을 완성해간다.

    https://docs.flutter.dev/development/ui/widgets

     

    Widget catalog

    A catalog of some of Flutter's rich set of widgets.

    docs.flutter.dev

     

    2. Flutter 기본 위젯들

    1) Scaffold: 한 페이지의 특정 영역에 위젯을 쉽게 배치할 수 있도록 틀을 잡아주며, 보통 가장 상위에 위치

    Scaffold(
    	appBar: 다른 위젯, // 상단 바
    	body: 다른 위젯, //화면 중앙에 가장 큰 면적
    	bottomNavigationBar: 다른 위젯, //하단 바
    	floatingActionButton: 다른 위젯, //우측 하단
    ),

     

    2) Column: 세로 방향으로 하위의 여러 위젯들을 나열

    Column(
      children: [ // 자식 위젯들
        Text("위젯1"),
        Text("위젯2"),
      ],
    ),

     

    3) TextField: 텍스트 입력을 받는다.

    TextField(
    	decoration: InputDecoration(
        	labelText: '이메일',
        ), // InputDecoration
    ), // TextField

     

    4) Button

    // 위로 올라와 있는 듯한 버튼
    ElevatedButton(
      onPressed: () {},
      child: Text('Elevated Button'),
    ),
    
    // 텍스트 버튼
    TextButton(
      onPressed: () {},
      child: Text('Text Button'),
    ),
    
    // 아이콘 버튼
    IconButton(
      onPressed: () {},
      icon: Icon(Icons.add),
    ),

     

    5) AppBar: 상단 바

    appBar: AppBar(
    			centerTitle: true,
                title: Text(
                	"Hello Flutter",
                	style: TextStyle(fontSize: 28),
                ), // Text
    		), // AppBar

     

    6) Padding: 안쪽 여백

    Padding(
        // 전방향
        padding: const EdgeInsets.all(8)
    
        //특정 방위만
        padding: const EdgeInsets.only(
                          left: 8,
                          right: 8,
                        )
    
        //위아래 또는 좌우
        padding: const EdgeInsets.symmetric(
                           vertical: 8,
                           horizontal: 8,
                        )
    
    )

     

    7) Container: 박스 형태의 기본 위젯, 다양하게 사용

    Container(
      width: 200, // 폭
      height: 200, // 높이
      color: Colors.amber, // 박스 색상
      child: Text("I Love Flutter!"), // 자식 위젯
    ),

     

     

    3. Dart 문법

    1) 변수

    // 변수 만드는 규칙
     1. 영문 / _ / $ / 숫자 만 사용
     2. 숫자로 시작 불가능
     3. camelCase 사용
    main(){
        // var : 변수 선언
        var name = '철수';
        var age = 20
    
        // runtime Type: 자료형 반환
        name.runtimeType; // String
        age.runtimeType; // int
    
        // 각종 자료형으로 선언
        String address = '우리집';
        int count = 30;
    
        // ?: 비어있을 수 있음(nullable)
        String? email; // null
    
        // final: 재할당 불가
        final phone = '010-0000-0000'; // 변경 불가
    }

     

    2) 자료형

        // String: 문자
        String firstName = '짱구';
        String lastName = '신';
    
        print(firstName + lastName); // 신짱구
        print(firstName + ' ' + lastName); // 신 짱구
        print('$firstName $lastName'); // 신 짱구
        print('${firstName + lastName}'); // 신짱구
    
        //split: 분할하여 리스트로 변경
        String domain = 'naver.com';
    
        print(domain.split('.')); // [naver, com]
        print(domain.split('')); // [n, a, v, e, r, ., c, o, m]
      int age = 20; // int: 정수
      double longitude = 127.634324; // double: 실수
      
    
      print(age.toDouble());   // int를 double로 변경
      print(longitude.toInt());  // double을 int로 변경 (소수점 버림)
      
      // 연산
      print(1 + 2); // 덧셈 = 3
      print(2 * 4); // 곱셈 = 8
      print(4 / 3); // 나누기 = 1.333...
      print(5 % 3); // 나머지 = 2
      print(5 ~/ 3); // 몫 = 1
        //bool: true, false
        print(!true); // !: not (false)
    
        // 비교 연산
        print(1 == 1); // 같다 (true)
        print(1 != 2); // 다르다 (true)
        print(1 > 2); // 크다, 작다 (false)
        print("hello" == 'hello'); // 문자열  비교 (true)
        // List: 배열
        List<String> fruits = ["바나나"];
    
        print(fruits.length); // 리스트 길이
    
        fruits.add('딸기') // 추가
        fruits.remove('딸기'); // 제거
    
        print(fruits[0]); // 0번째 원소 조회
        fruits[0] = '키위'; // 0번째 원소 수정
    
        // 다양한 자료형 포함한 배열
        List<dynamic> buckets = [1, "문자", [1, 2]];
        print(buckets[2][1]); // 2번째 원소(배열)의 1번째 값 조회
        // Map: {'key': 'value'}
    
        Map<String, dynamic> person = {
            "name": "철수",
            "age": 20
        };
    
    	print(person['name']); // 조회
        person['email'] = 'hi@mail.com'; // 추가
        person['age'] = 10; // 수정
        person.remove('name'); // 삭제

     

    *dynamic vs var

        //dynamic: 모든 자료형 가능
        dynamic name = "철수"; // String 담기
        name = 20; // int 담기
    
        // var: 처음 담긴 자료형만 가능
        var age = 20;
        age = '철수'; // ERROR

     

     

    3) 흐름 제어문

    // 조건문
    if (bool1) {
    	// bool1이 true면 실행
    } else if (bool2) {
    	// bool1이 false이고, bool2가 true이면 실행
    } else {
    	// bool1, bool2가 모두 false이면 실행
    }
    
    // && : AND
    if (false && true) {
    print('&&는 하나라도 true가 아니면 실행이 안됩니다.');
    } else if (true && true) {
    print('&&는 양쪽 모두 true면 실행이 됩니다.');
    }
    
    // || : OR
    if (false || false) {
    print("||는 둘다 false면 실행이 안됩니다.");
    } else if (false || true) {
    print("||는 둘 중 하나라도 true면 실행이 됩니다.");
    }

     

    4) 함수

    void main() {
      say(from: "영희");
      say(from: "영희", message: "안녕?");
      say(message: "안녕?", from: "영희"); // 이름 지정 매개변수는 순서 변경 가능
    }
    
    // required: 필수
    void say({required String from, String? message}) {
      print("$from : $message"); //
    }
    
    
    // 화살표 함수: 위 아래 동일한 함수
    void hi(){
    print('hi');
    }
    
    void hi() => print('hi');

     

    5) 클래스

    void main() {
      // instance 생성
      Bread bread1 = Bread('팥');
      Bread bread2 = Bread('크림');
      WhiteBread whiteBread = WhiteBread('감자');
    
      print(bread1.content); // property 호출 (팥)
      print(bread2.getDescription()); // method 호출 (맛있는 크림빵입니다.)
      print(whiteBread.getDescription()); // method 호출 (맛있는 감자빵은 흰빵입니다.)
    }
    
    class Bread {
      // property(속성): class 속 변수
      String? content;
    
      // constructor(생성자): 클래스명과 동일한 함수
      Bread(String core) {
        content = core;
      }
    
      // method(메소드): class 속 함수
      String getDescription() {
        return "맛있는 $content빵입니다.";
      }
    }
    
    // 상속: Bread의 변수와 함수를 그대로 전달받음
    class WhiteBread extends Bread {
      WhiteBread(super.core); // constructor에 상위 클래스의 파라미터 넣어줌.
    
      // override: 상속받은 값 덮어쓰기
      @override
      String getDescription() {
        return "맛있는 $content빵은 흰빵입니다.";
      }
    }

     

    반응형

    댓글

© 2023. titann all rights reserved