Flutter: Functions vs Classes(Widgets)

루시Soo의 우와한 서재·2022년 5월 30일
0

시작하기 전에

What is library in Dart?

  • A library in a programming language represents a collection of routines (set of programming instructions). Dart has a set of built-in libraries that are useful to store routines that are frequently used. A Dart library comprises of a set of classes, constants, functions, typedefs, properties, and exceptions.

  • fluuter에서는 기본적으로 상위 라이브러리에서 제공하는 classes를 이용해서 코드를 작성하는데 반환되는 데이터값에 따라 functions를 사용해야하는 경우도 있다.

  • 대표적으로 안드로이드와 구글관련 앱 개발에 사용되는 material package와 ios스타일의 앱을 구현할 수 있게 도와주는 cupertion 등이 있다.



본론

What is the Difference Between Functions and Classes to Create Reusable Widgets?

  • There is an important difference between using functions instead of classes, that is: The framework is unaware of functions, but can see classes.

  • class는 앞에 const가 붙을 수 있지만 function은 붙을 수 없다. const는 const가 붙은 class코드가 계속 build되는 것을 막아줄 수 있어 더 효율적인 코딩을 가능하게 해준다.

  • class와 function은 inter-compatible(상호 호환적)이다. 따라서, class로 작성된 component를 function으로 바꾸는 것이 가능하다.



결론

Why should we use Classes instead of Functions?

  • 프레임워크가 알아차린다는 의미는 바꿔말하면 classes를 사용한 코드는 프레임워크로 인해 최적화가 가능하고 또한 버그를 프레임워크가 감지하여 더 나은 error msg를 보내준다는 의미이고, 본론에서도 이야기했듯이 const의 사용이 가능함으로써 더 효율적이다. 반면, functions을 사용한 코드는 더 간결하다는 것이외에는 다른 장점이 없다.



예시코드 (test it with DartPad)

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.lightBlue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  
  _MyHomePageState createState() => _MyHomePageState();
}

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

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
  
  // if there is any change by setState() calling, the code below in build will be rebuilt.  
  // it can cause a 
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        foregroundColor: Colors.white70,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //default code was the one below wih Text widget. 
            /*const Text(
              'You have pushed the button this many times:',
            ),*/
             
            // if there is no const contructor insid your _Description StateWidget, error occured. 
            const _Description(), // change it to _description() for testing the code as function 
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  //_description function
  // if you want to test it, activate the funtion code but deactivate class _Description
  // by test, you can see _description as fuction is rebuilt at anytime setSate() is called in Console.
  // function must be located inside _MyHomePageState class
  
  /*_description() {
    print('_description is getting rebuilt');
    return Text('You have pushed the button this many times:');
  }*/
}

  // class name starts with a big letter
  // const can be used for the class. if const is used, the print() in build will appear only once. 

  class _Description extends StatelessWidget {
    
    //to use const for the class, you need const constructor.You can delete it anytime, when
    // you don't use const for the class. 
    const _Description();
    
    
    Widget build(BuildContext context) {
      print('_description is getting rebuilt');
      return Text('You have pushed the button this many times:');
    }
  }


참조자료

https://flutter-developer.medium.com/flutter-difference-between-functions-and-classes-to-create-reusable-widgets-170b2a443a73

https://www.youtube.com/watch?v=i1nBzE30wvk&t=326s

profile
그냥 끄적끄적 공부 정리 블로그

0개의 댓글