1. 객체지향언어에서의 상속

객체지향언어에서는 코드의 재사용성을 위해 상속을 사용하기도 한다.

실제로 라이브러리의 유용한 클래스를 상속받아 프로젝트에 맞게 커스터마이징을 한 후 사용하기도 한다.

 

2. 플러터의 구조

플러터는 기본적으로 위젯이라는 객체들로 구성되어있으며 하나의 위젯트리를 형성한다.

앱의 기본이 되는 MaterialApp과 Scaffold역시 위젯이며 이 위젯을 시작으로 수 많은 자식 위젯들로 하나의 앱이 완성된다.

플러터는 수 많은 위젯들을 준비하여 두었고 우리는 그 위젯들을 적재적소에 구성하기만 하면된다.

가령

가운데 정렬을 하고싶다 : Center 위젯

버튼을 삽입하고싶다 : ElevatedButton 위젯

이미지를 삽입하고싶다 : Image 위젯

가운데 정렬된 버튼 안에 이미지를 삽입하고싶다 : Center - ElevatedButton - Image

처럼말이다.

 

3. 위젯을 상속

프로젝트를 진행하다보면 프레임워크나 라이브러리에서 제공하는 위젯만 가지고는 필요한 기능이 부족할 수 도 있다.

그럴땐 보통 위의 설명과 같이 클래스를 상속받아 기능을 확장하는것이 일반적인데..

실제로 위젯을 상속받아 구현을 해보려고 했지만 생성자의 구성과 Null safty 로 인해 아무 기능도 확장도 하지않은 클래스가 이미 복잡해져버려서 정상적인 위젯의 상속방법을 찾아 검색에 나섰다.

기본적인 Dart 문법으로 상속을 하는 예제는 많았지만 이미 정의된 위젯을 상속받는 예제는 찾아 볼 수 없었고 그 대신 아래와 같은 글을 찾을 수 있었다.

https://stackoverflow.com/questions/51476234/subclass-a-class-that-extends-statelesswidget-or-statefulwidget-class

 

Subclass a class that extends StatelessWidget or StatefulWidget class

Is it possible to create a class that extends a class extending StatelessWidget or StatefulWidget. For example: class MyButton extends StatelessWidget { final String label; Button({this.label}); @

stackoverflow.com

https://flutter.dev/docs/resources/faq#can-i-extend-and-customize-the-bundled-widgets

 

FAQ

Frequently asked questions and answers about Flutter.

flutter.dev

 

Can I extend and customize the bundled widgets?

Absolutely. Flutter’s widget system was designed to be easily customizable.

Rather than having each widget provide a large number of parameters, Flutter embraces composition. Widgets are built out of smaller widgets that you can reuse and combine in novel ways to make custom widgets. For example, rather than subclassing a generic button widget, ElevatedButton combines a Material widget with a GestureDetector widget. The Material widget provides the visual design and the GestureDetector widget provides the interaction design.

To create a button with a custom visual design, you can combine widgets that implement your visual design with a GestureDetector, which provides the interaction design. For example, CupertinoButton follows this approach and combines a GestureDetector with several other widgets that implement its visual design.

Composition gives you maximum control over the visual and interaction design of your widgets while also allowing a large amount of code reuse. In the framework, we’ve decomposed complex widgets to pieces that separately implement the visual, interaction, and motion design. You can remix these widgets however you like to make your own custom widgets that have full range of expression.

 

4. 결론

위 글들의 결론은 플러터에서 이미 만들어진 위젯(StatelessWidget 또는 StatefulWidget위젯을 이미 상속받은 위젯)의 기능을 추가하기 위해 위젯을 상속 받는것이 불가능한것은 아니지만 상속이 아닌 구성을 추천한다는 것이다. 

이 방법이 익숙치는 않지만 mixin키워드와 같은 키워드와 더불어 원하는 위젯을 만드는데 어려움은 없어보인다

+ Recent posts