ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Flutter] 기본적인 구조
    Flutter/FLUTTER 2023. 9. 4. 12:45
    void main() {
      runApp(MyApp());
    }

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

      @override
      Widget build(BuildContext context) {
        return ChangeNotifierProvider(
          create: (context) => MyAppState(),
          child: MaterialApp(
            title: 'Namer App',
            theme: ThemeData(
              useMaterial3: true,
              colorScheme: ColorScheme.fromSeed(seedColor: Color.fromARGB(255, 68, 207, 142)),
            ),
            home: MyHomePage(),
          ),
        );
      }

    }


    StatelessWidget을 상속 받는 MyApp

    StatelessWidget은 UI가 동적으로 변동되지 않는 (고정된) 위젯임을 나타냄.

    반대로 UI가 동적으로 변경된다면 StatefulWidget

    MyApp 내부에 어떠한 변수가 있어서 사용자의 조작에 따라 변수가 바뀐다면, StatefulWidget을 상속받아야 하는데,

    그 이유는 변수가 변경되었을 때, 변경되었음을 알리고 UI를 다시 그려야 하기 때문임!

    StatefulWidget 내부에서 변경됨을 알리는 메서드는 setState()

     

    내부의 build 메서드가 ChangeNotifierProvider를 리턴하는데, ChangeNotifier 클래스에 변동사항이 있을 경우 UI를 다시 그리는 역할을 함

    여기서 변동사항이 있다고 해서 Stateful이 아니다. 변동사항이라 함은 MyAppState의 변동사항일 뿐이고, MyApp의 변동사항이 아님.

    MyApp이 그리고 있는 형태는 변화가없기 때문에 Stateless

     

    class MyAppState extends ChangeNotifier {
      var current = WordPair.random();

      void getNext(){
        current = WordPair.random();
        notifyListeners();
      }

      var favorites = <WordPair>[];

      void toggleFavorite() {
        if(favorites.contains(current)){
          favorites.remove(current);
        }else{
          favorites.add(current);
        }
        notifyListeners();    
      }

    }

     

    notifyListeners(); 가 MyAppState 내부의 변동사항을 알리는 메서드.

    ChangeNotifier::notifyListeners() 임

     

     

    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        var appState = context.watch<MyAppState>();
        var pair = appState.current;

        return Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                BigCard(pair: pair),
                SizedBox(height: 20,),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ElevatedButton(
                      onPressed: () => appState.toggleFavorite(),
                      child: Text("Like"))
                    ,
                    ElevatedButton(
                      style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.red)),
                      onPressed: ()=>appState.getNext(),
                      child: Text("Next"),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      }
    }

     

    var appState = context.watch<MyAppState>();

    이 부분은, MyAppState 클래스의 인스턴스를 찾아 반환하여 appState 변수에 할당하는 코드.

    이를 통해 MyAppState 내부의 변수와 메서드에 접근할 수 있다.

     

     

     

    Widget build(BuildContext context) {

    build 메서드 마다 매번 나오는 매개변수 BuildContext context

     

    간단하게 BuildContext를 정리하면, (GPT의 설명)

    BuildContext는 Flutter 앱에서 위젯 트리의 위치 및 구성 정보를 나타내는 객체입니다. 이 객체는 앱의 다양한 부분에서 사용되며, 앱의 레이아웃 및 동작을 제어하는 데 중요한 역할을 합니다.

     

    자세한 내용을 풀자면 엄청 길고..

    BuildContext 자체로만 따로 정리를 해야할듯 함

     

    일단 지금은

    BuildContext는 build 메서드가 나올때 무조건 매개변수로 들어가며,

    BuildContext가 어플리케이션을 동적으로 조작할 수 있도록 해준다고 이해하고 넘어가자

     

     

     

    결론적으로, 플러터 앱의 기본 구성은

    앱의 전반적인 형태를 그리는 StatelessWidget,

    변동사항에 따라 앱을 동적으로 그려주는 StatefulWidget 두가지이다.

     

    위의 코드들에서는 StatefulWidget을 사용하지 않았지만, ChangeNotifier 클래스가 StatefulWidget을 기반으로 상태를 관리하는 클래스다.

    이것은 StatefulWidget을 직접 사용하지 않고 Provider 패키지를 활용하여 간단히 상태를 관리하는 방법중 하나라고 한다.

     

    'Flutter > FLUTTER' 카테고리의 다른 글

    [FLUTTER] 231005 기억나는것들 간단하게 정리  (0) 2023.10.05
    [FLUTTER] TIL  (0) 2023.09.13
    [FLUTTER] TIL  (0) 2023.09.08
    [FLUTTER] TIL  (0) 2023.09.06
    [FLUTTER] TIL  (0) 2023.09.05
Designed by Tistory.