관리 메뉴

피터의 개발이야기

[flutter] Hello Flutter 앱 만들기 본문

Programming/Flutter

[flutter] Hello Flutter 앱 만들기

기록하는 백앤드개발자 2024. 2. 18. 16:46
반응형

ㅁ 들어가며

 코드팩토리의 플러터 프로그래밍 책을 보며 실습한 내용을 정리하였다.

지난 글인, [Flutter] Flutter 맥북 개발환경 세팅하기에서 개발환경을 세팅하고 샘플 코드를 다운받아 emulator를 작동하는 과정까지 정리하였다. 이번 글에서는 프로젝트를 생성하는 과정을 정리하였다.

소스는 이곳에 있다.

 

ㅁ  프로젝트 생성

 ㅇ 안드로이드 스튜디오에서 프로젝트를 생성

 

ㅁ 기본 Demo 프로젝트가 생성됨

 ㅇ 기본적으로 프로젝트만 생성하였는데, 데모 코드가 생성되어 emulator까지 작동 가능한 상태였다.

 ㅇ 기본 제공되는 소스는 https://docs.flutter.dev/get-started/test-drive에서 자세히 설명하고 있다.

import 'package:flutter/material.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.brown),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

 

ㅁ Hello Code Factory 출력

// Hello Code Factory 텍스트 출력해 보기
void main() {
  runApp(
    // material은 디자인과 관련된 기능 제공
    MaterialApp(
      home: Scaffold( // Scaffold 위젯
        body: Text( // 텍스트 출력
          'Hello Code Factory',
        ),
      ),
    )
  );
}


//텍스트 중앙정렬 테스트
void main() {
  runApp(
    // material은 디자인과 관련된 기능 제공
    MaterialApp(
      home: Scaffold( // Scaffold 위젯
        body: Center(
          child: Text( // 텍스트 출력
            '텍스트 중앙정렬 테스트',
          ),
        ),
      ),
    )
  );
}

 ㅇ 기본 데모 소스를 주석하고 Hello Code Factory 텍스트를 출력해 보았다.

 ㅇ 텍스트 중앙정렬 테스트를 진행.

 

ㅁ 마무리

ㅇ 플로터는 Embedder, Engine, Framework로 구성된다.

   - Embedder: 네이티브와 통신

   - Engine: 플러터의 중심 기능 제공

   - Framework: 플러터의 실질적인 코드가 구현되는 공간

ㅇ 코드는 함수형태로 구현

   - 중앙정렬을 위해서 Center() 함수에 Text() 객체를 주입시켜 실행된다.

 

ㅁ 함께 보면 좋은 사이트

 flutter cookbook - Build a Flutter layout

  ㄴ 플루터 쿡북 중 레이아웃 페이지 링크

ㅇ codelabs- 첫 번째 Flutter 앱

  ㄴ 환경을 잡고 테스트를 해보기 좋은 튜토리얼

반응형
Comments