본문 바로가기
Flutter

[Flutter] 기본 제공 코드 뜯어보기

by 배잼 2022. 2. 21.

매번 봐도 도저히 기억이 안나서... 메모해두려고 한다.

** import 꼭 하기 !!

 

void main() {
  runApp(const MyApp());
}
  • 컴파일러에게 시작을 알리기 위한 main() 함수
  • 플러터 최상위 함수 runApp( )
  • MyApp라는 커스텀 위젯을 넣어준다.
class MyApp extends StatelessWidget {

	//key-value 형식의 생성자를 만든다. 
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
  • `statelessWidget`이다! (위젯을 만들 때는 statefulWidget인지 고민해봐야 한다.) 데이터의 상태가 변하지 않는 위젯.
  • `MeterialApp` : `package:flutter/material.dart` 에서 제공
  • `primarySwatch` : 특정 색의 음영을 기본 색상으로 지정하겠다는 의미다.
  • VS 코드에서는 위젯의 끝을 알려주는 기능이 있다.
  • 모든 커스텀 위젯은 다른 위젯을 리턴하는 Build 함수를 가지고 있다.
  • `BuildContext` : A handle to the location of a widget in the widget tree. 위젯 트리에서 어디에 위치하는지, context라는 정보를 넣어 리턴해준다는 뜻이다.
  • home은 앱이 정상적으로 실행되었을 때 가장 먼저 화면에 보여주는 경로다. Myhomepage라는 커스텀 위젯을 적어줬다. 이때, title를 넘겨줬다.
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  • StatefulWidget 이다! 데이터의 상태가 변하는 위젯이다.
  • required : null-safety를 위함. 필수 파라미터가 들어오지 않으면 에러를 던진다
  • createState() : StatefulWidget는 life cycle을 가진다. 객체를 생성하면 생성자가 호출되고, 그 다음으로 호출된다. 필수적으로 override해야한다. State 객체를 생성한다.
  • State<MyHomePage> : 공식문서 참조하는게 좋을 듯! StatefulWidget의 논리 및 내부 상태라고 한다.
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      // 이어서
  • Scaffold : 앱 화면에 위젯을 배치하기 위한 도화지 역할. 위젯이 리턴되었을 때 부모 위젯의 context를 그대로 물려받는다. (부모 : _MyHomePageState)
  • Scaffold 의 위치 알아내기 : Scaffold의 자식 위젯의 context를 통해 알아내야 함.
  • appBar() 위젯 내에 타이틀을 넣을 수 있다.
  • setState : State Object는 setState method를 호출해서 자발적으로 subtree를 rebuild할 수 있다. 내부 데이터가 변경되었음을 알리는 데 사용(공식 문서 참조). (react hook 같은 느낌?)
body: Center(
        child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
 // 이어서
  • body : the primary content of the scaffold
  • center 위젯을 불러오면 중앙 정렬 가능
  • column 위젯 : 자신의 모든 내용을 세로로 배치하는 위젯, child가 아니라 children이다! (세로 배치는 하나면 의미가 없다)
  • mainAxisAlignment : 메인축을 center로 한다. (start, end, spaceEvently 등이 있다.)
  • <Widget>[ ] : 배열의 의미다. 넣으려고 하는 것들을 쉼표로 구분해가며 넣어주면 된다.
  • Theme.of(context): 위젯 트리에서 가장 가까운 Theme을 리턴한다.

 

floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
  • FloatingActionButton 위젯이다.
  • onPressed : callback 함수로, 눌렀을 때 호출된다.
  • tooltip : 길게 눌렀을 때 뜨는 텍스트
  • icon : 넣고자 하는 이미지

이렇게 해서 누르면 숫자가 오르는 앱 예제를 분석해 봤다!

ref

https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html

https://api.flutter.dev/flutter/widgets/State-class.html

https://api.flutter.dev/flutter/widgets/State/setState.html

댓글