ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 부트캠프창{창업일지}# 1주차 함수,클래스(실습)
    부트캠프{창} 2022. 6. 3. 23:40

    주요 프로젝트때문에 회사에서도 야근하고 너무 힘들다 ㅠㅠ

    기본설치 과정에서 시간을 너무 많이 버렸는데 에뮬레이터 실행 안되시는분들중에 

    구글 뒤져서 다 안되시는분들은 혹시 드라이버에 용량문제 일수도 있습니다 ㅠㅠ 최소 30기가 정도이상

    여유를 주고 사용하시기를.....

     

    함수는 여러 코드를 묶어둔 상자

    *Main 역시 함수이다.

     

    void say() {

      say("철수");

    }

     

    void say(String person) {

       print(person + "야 안녕?");

    }

     

    결과값 : 철수야 안녕?

     

    say("철수"); <- 입력값

     

    void say(String person) <- 입력값을 받을 변수

     

    *person은 변수의 이름이기 때문에 원하는 다른 이름으로 변경가능

    함수의 입력값을 받아주는 변수를 흔히 파라미터/매개변수/인자등 다양하게 부릅니다.

     

    함수에 입력값을 여러개 받는 방법

    void main() {
     say("상필", "우섭야 안녕?");
    }

     

     

     

     

    함수의 출력
    void say(String from, String message) {
      print("$from : $message"); 
    }

     

    void main() {
      String name = getName();
      print(name);
    }

    String getName() {
      return "상필";
    }

     

     

    return -> 결과를 출력(반환)하는 방법

     

    ----------------------------------------------------------


    void main() {
      String bread = getBread("팥");
      print(bread);
    }

    String getBread(String material) {
      return material + "빵";
    }

     

    *팥을 변수값으로 받고 출력을 빵과 + 팥으로 돌려준다

    그러면 함수는 팥빵이 출력!!!

     

     

    클래스

    클래스 구성요소

    속성 : 클래스 내의 변수

    메소드 : 클래스 내의 함수

    생성자 : 클래스 명과 동일한 함수

     

    앞에서 배운 변수와 함수로 이루어져 있다.

     

    class Bread {

    // Bread 클래스가 가진 content 속성
    String content = "팥";

    }

    *클래스 내의 함수를 메소드라 부른다.

     

    class Bread {

    String content = "팥";

    // Bread 클래스가 가진 getDescription 메소드
    String getDescription() {
        return "맛있는 $content빵입니다."; // 맛있는 팥빵입니다.
      }
    }

    *클래스 내의 함수를 메소드

     

    인스턴스(Instance)

    void main() {
      // 인스턴스(instance) 만들기
      Bread bread1 = Bread('팥'); // 클래스의 생성자를 호출하여 인스턴스(instance)를 만듭니다.
      Bread bread2 = Bread('크림');
      
      // 속성 호출
      print(bread1.content); // 팥
      print(bread2.content); // 크림
      
      // 메소드 호출
      print(bread1.getDescription()); // 맛있는 팥빵입니다.
      print(bread2.getDescription()); // 맛있는 크림빵입니다.
    }

    class Bread {
      String? content; // 클래스 속 변수를 속성(property)라고 부릅니다.
      
      Bread(String core) { // 클래스명과 동일한 이 함수를 생성자(constructor)라고 부릅니다.
        content = core;
      }
      
      String getDescription() { // 클래스 속 함수를 메소드(method)라고 부릅니다.
        return "맛있는 $content빵입니다.";
      }
    }

     

    상속예제

    void main() {
      Bread bread = Bread();
      Cookie cookie = Cookie();
      
      print(bread.madeBy); // TousLesJours
      print(cookie.madeBy); // TousLesJours
    }

    // 빵 : TousLesJours를 상속받음(=변수와 함수를 그대로 전달받음)
    class Bread extends TousLesJours {
     
    }

    // 쿠키 : TousLesJours를 상속받음(=변수와 함수를 그대로 전달받음)
    class Cookie extends TousLesJours {
      
    }

    // 뚜레쥬르
    class TousLesJours {
      String madeBy = "TousLesJours";
    }

     

    - Dart의 모든 것은 Class로 구성

     

     

     

    실습1 - Food Recipe 만들기

     
     
    *최종코드
    import 'package:flutter/material.dart';

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

    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: HomePage(), // 홈페이지 보여주기
        );
      }
    }

    class HomePage extends StatelessWidget {
      const HomePage({Key? key}) : super(key: key);

      @override
      Widget build(BuildContext context) {
        // 음식 사진 데이터
        List<Map<String, dynamic>> dataList = [
          {
            "category": "수제버거",
            "imgUrl": "https://i.ibb.co/pnZK1rz/burger.jpg",
          },
          {
            "category": "건강식",
            "imgUrl": "https://i.ibb.co/7KLJjJV/salad.jpg",
          },
          {
            "category": "한식",
          },
          {
            "category": "디저트",
            "imgUrl": "https://i.ibb.co/HhGRhds/dessert.jpg",
          },
          {
            "category": "피자",
            "imgUrl": "https://i.ibb.co/QdDtTvt/pizza.jpg",
          },
          {
            "category": "볶음밥",
          },
        ];

        // 화면에 보이는 영역
        return Scaffold(
          appBar: AppBar(
            iconTheme: IconThemeData(color: Colors.black),
            elevation: 0,
            backgroundColor: Colors.white,
            title: Text('Food Recipe',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                )),
            actions: [
              IconButton(onPressed: () {}, icon: Icon(Icons.person_outline))
            ],
          ),
          body: Column(children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                decoration: InputDecoration(
                    hintText: "상품을 검색해주세요.",
                    border: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.black),
                    ),
                    suffixIcon: IconButton(
                      icon: Icon(Icons.search),
                      onPressed: () {},
                    )),
              ),
            ),
            Divider(height: 1),
            Expanded(
              child: ListView.builder(
                itemCount: dataList.length,
                itemBuilder: (context, index) {
                  String category = dataList[index]['category'];
                  String imgUrl = dataList[index]['imgUrl'];

                  return Card(
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        Image.network(
                          imgUrl,
                          width: double.infinity,
                          height: 120,
                          fit: BoxFit.cover,
                        ),
                        Container(
                          width: double.infinity,
                          height: 120,
                          color: Colors.black.withOpacity(0.5),
                        ),
                        Text(
                          category,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 36,
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ]),
          drawer: Drawer(
            child: Column(
              children: [
                DrawerHeader(
                  margin: const EdgeInsets.all(0),
                  decoration: BoxDecoration(color: Colors.amber),
                  child: SizedBox(
                    width: double.infinity,
                    child: Column(
                      children: [
                        CircleAvatar(
                          radius: 36,
                          backgroundColor: Colors.white,
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Image.network(
                              "https://i.ibb.co/CwzHq4z/trans-logo-512.png",
                              width: 62,
                            ),
                          ),
                        ),
                        SizedBox(height: 16),
                        Text(
                          "닉네임",
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Text(
                          "hello@world.com",
                          style: TextStyle(
                            fontSize: 16,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                AspectRatio(
                  aspectRatio: 3 / 1,
                  child: PageView(
                    children: [
                      Image.network("https://i.ibb.co/0mXKmZq/banner-1.jpg"),
                      Image.network("https://i.ibb.co/DDgYrJR/banner-2.jpg"),
                      Image.network("https://i.ibb.co/v1RMHN4/banner-3.jpg"),
                      Image.network("https://i.ibb.co/NmNsrr2/banner-4.jpg"),
                    ],
                  ),
                ),
                ListTile(
                  title: Text(
                    "구매내역",
                    style: TextStyle(fontSize: 18),
                  ),
                  trailing: Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.black,
                  ),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
                ListTile(
                  title: Text(
                    "저장한 레시피",
                    style: TextStyle(fontSize: 18),
                  ),
                  trailing: Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.black,
                  ),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            ),
          ),
        );
      }
    }

     

    교육시간이 부족해서 완전히 혼자서 하지는 못하고 교육자료를 보면서 따라 만들었다.
    이번주 일요일날 복습을 해서 완전히 따라가야겠다 ㅠㅠ

Designed by Tistory.