Learn to share,Share to learn

5월 둘째주 공부 기록서 - 위젯간 데이터 넘겨주기, state, this, get 본문

Flutter/주간별 공부 기록서

5월 둘째주 공부 기록서 - 위젯간 데이터 넘겨주기, state, this, get

Rogue One 2021. 5. 13. 20:19

5월 12일

 

medium.com/swlh/the-simplest-way-to-pass-and-fetch-data-between-stateful-and-stateless-widgets-pages-full-2021-c5dbce8db1db

 

Easy Ways to Pass and Receive Data With Flutter Stateful and Stateless Widgets or Pages

2021 Novice App Developers Guide

medium.com

위젯간의 데이터를 넘겨주는법에 관한 글이다.

넘겨받을 위젯에 파라미터를 작성하고, 넘겨줄 위젯에서 파라미터를 넣어 보낼 위젯을 호출한다.

이게 가장 기초 방법인데, 연결되어있지 않을때는 어떻게 하는지 공부하기

 

 

 

플러터의 모든 widget 클래스는 반드시 빌드 메서드를 갖는다. 하지만 statefulwidget클래스는 빌드 메서드를 포함하지 않는대신, 상태 객체를 포함하며, 모든 상태 객체는 빌드 메서드를 포함한다. 스테이트풀위젯과 스테이트는 같은 개체라고 생각해도 무방하다. 

 

스테이트풀 위젯을 보면, 

class Homepage extends StatefulWidget{
	@override 
    _MyHomePageState createState() => _MyHomePageState();
    }

와 같이, 모든 스테이트풀 위젯은 스테이트 객체를 반환하는 createState 메서드를 반드시 정의해야 한다. 또 위의 @override는 슈퍼클래스의 메서드 createState를 오버라이드 하는것이다.

 

이렇게 생성된 상태클래스는 플러터의 state 클래스를 상속받는다

class _MyHomePageState extends State<MyHomePage>{

	@override
    Widget build(BuildContext context) {
    
    //......
    
    	}
}

 

setState는 스테이트풀 위젯에서 메서드를 실행하면서 설정이 바뀐 모든 위젯을 다시 그리는데, 비동기 코드를 실행할수 없다는점을 주의해야한다.

예를 들어, 인터넷에서 gif를 가져오는 api를 사용할때, 이미지가 준비되지 않은 상태에서 setState를 호출하는 일은 없어야한다.

 

key 부분 더 공부하기

 

 이 두 부분을 통해 어떻게 클린 아키텍쳐로 페이지 들을 구성할수 있을지 알게되었다. view는 stateful widget을 상속한다. 이렇게 만든 view는 stateful 의 속성을 가지고 있으며, 생성시에 controller와 연결되어 controller가 주는 데이터를 화면에 그려준다. 이때 controller는 view로 부터 받은 데이터와 repository를 이용해 presenter, usecase와 연결되고 데이터를 돌려준다고 보면 되겠다. 일단은 여기까지 이해하고 더 공부하여보자.

 

5월 13일

stackoverflow.com/questions/64324559/what-does-mean-of-using-the-this-keyword-in-dart

 

What does mean of using the "this" keyword in Dart?

I'm sorry if this sounds like an extremely foolish question but it's really been bugging me. What is the "this." that I see? Whenever I see the documentation in flutter I see it used in t...

stackoverflow.com

Dart와 같은 언어에서 this의 의미는 무엇일까? 지금까지는 단순히 생성자에 넣어주면서 인수로 들어올때 클래스 내부변수와 인수의 이름이 같을때 명확히 구분하기 위해서 사용 한다고만 생각했었다. 물론 당연히 맞는말이다. 내가 이부분을 헷갈린 이유는 flutter 코드를 작성하면서 생성자를 만들때, 생성자를 작성하려는 Class안에 변수가 있을시 생성자에 this.변수명 이 있는경우를 보고 어떤방식으로 작동하는지 이해하지 못해서 였다. 다음 내용을 보면 이해가 빠를것이다.

brunch.co.kr/@mystoryg/123

 

09화 다트 생성자 (Constructor) (1/2)

플러터를 위한 다트 프로그래밍 | 다트의 생성자 (1/2) 클래스에는 생성자가 따른다. 생성자는 이름처럼 클래스가 인스턴스화 될 때, 즉 객체가 생성될 때 호출된다. 클래스를 알게 되고 마주친

brunch.co.kr

brunch.co.kr/@mystoryg/124

 

10화 다트 생성자 (Constructor) (2/2)

플러터를 위한 다트 프로그래밍 | 다트의 생성자 (2/2) 이전 글에 이어서 다음 세 가지 생성자에 대해서 알아본다. 리다이렉팅 생성자(Redirecting constructor) 상수 생성자(Constant constructor) 팩토리 생

brunch.co.kr

papabee.tistory.com/37

 

플러터, flutter) Dart의 생성자 & Named Arguments

저번에 설명했던 코드의 일부분입니다. 저기 보면 MaterialApp이라는 생성자 안에 home: 이렇게 표시된 부분이 있습니다. 오늘은 여기에 관하여 자세히 다루어보고자 합니다. 우리는 class를 만들고

papabee.tistory.com

특히 마지막 링크가 아주 도움이 되었다. 생성자를 만들때, 클래스 내부에 변수를 값을 받아 초기화(할당) 해줄때가 있다. 예를 들어, 클래스 내부의 정보를 다른 클래스에 보낸다고 했을때, 다른 클래스의 생성자안에 변수를 만들고 그 변수에 값을 받을수 있다. 이때 생성자를 단순히

this.name과 같이 사용하면, 현재 인스턴스 내의 name에 받은 인자를 넣어주는것과 같다. 이때 {}는 인자를 보내줄때 name:'aaa'와 같이 작성할수 있도록 해주는부분이다. 이부분은 이미 작성해봤기에 알고있었는데 정확히 어떻게 동작하는지 알게되었다.

 

https://stackoverflow.com/questions/54426802/what-does-mean-in-dart

 

What does "< >" mean in Dart?

Through an online Dart course, I've found some values bracketed with "less than" and "greater than" marks such as "List< E >". e.g. List fixedLengthList = new List(5); I couldn't f...

stackoverflow.com

<>의 경우, 어떤 타입을 받을지 지정해주는 역할을 한다. Person<String> 을 해준다면 person의 인수로 null이나 string만을 받는다는 뜻!

https://ska0225.tistory.com/14

 

DART => 화살표 코드 의미

기본적인 게 매번 헷갈림 손에 익숙해질때까지 자주 쓰는 수밖에 동일한 코드 =>  는 {return} 과 동일 1 줄만 사용 가능 / Single line expression Return 값 없는 void에도 사용 가능 arrow syntax 화살표 문법

ska0225.tistory.com

화살표 함수는 코드 한줄일때 간단히 하기 위해서~

 

생성자 이후 콜론 뜻 공부하기

 

5월 14일

 

https://stackoverflow.com/questions/54518642/what-is-the-difference-between-widget-sample-and-widget-get-sample

 

What is the difference between Widget sample and Widget *get* sample?

beginner in Flutter here, Does anybody know the difference, or significance of the keyword get in the context of instantiating a widget? I'm declaring a widget here ListTile sampleListTile { r...

stackoverflow.com

코드중 get을 사용한 위젯이 눈에 갑자기 들어왔다. 지금까지는 그런갑다 하고 넘어갔는데 무슨 뜻일까?

https://dart.dev/guides/language/language-tour#getters-and-setters

 

A tour of the Dart language

A tour of all the major Dart language features.

dart.dev

https://brunch.co.kr/@mystoryg/127

 

13화 다트 Getter & Setter

플러터를 위한 다트 프로그래밍 | 다트의 Getter와 Setter 클래스의 멤버 변수를 private이 아닌 public으로 선언하면 아무 곳에서나 접근이 가능하다. 아무데서나 막 쓸 수 있으니까 우와 너무 편하다!!

brunch.co.kr

위 두 레퍼런스들을 참고하여 알게 되었다. 일단 get은 getter다. get을 이용하지 않을경우 위젯을 만들때 Widget sample() { ... } 와 같이 만들어야 하며, 그러지 않고 단순히 Widget sample { ... } 을 작성할시, 인스턴스 생성에 { .. } 를 붙인것과 다를바 없어진다. 

 

getter를 사용해 Widget get sample { .. } 로 작성한다는것은 어떤의미일까?

간단히 말하자면, 읽기전용으로 만드는것이다. 외부의 요인이 클래스 내부를 변화시키지 못하고, 값만 받아올수 있게하여 독립적이게 만드는것이다.

 

Flutter initialize listhttps://flutterbyexample.com/lesson/initializer-lists-and-final-properties

 

Initializer lists and final properties

Class fields in Dart can be `final`. Marking a field as `final` tells Dart that this variable can never be re-assigned. Importantly, this doesn't mean that the variable must be declared and assigned at the same time. Often, you'll use the `final` keyword f

flutterbyexample.com

 

https://stackoverflow.com/questions/50274605/colon-after-constructor-in-dart

 

Colon after Constructor in dart

This code is from flutter gallery and i'm trying to understanding and adapting it. I would know what this syntax means: class DemoItem { DemoItem({ this.valueName, this.hintName...

stackoverflow.com

생성자 뒤에 :, 즉 콜른이 붙는경우가 있다. 이때는, 생성자의 값에 접근할수 있는 리스트를 만드는것이다. 

즉, 생성자가 생성되고, run 되기 전에, 새 인스턴스에 생성자의 파라미터를 assign 할수 있는 기능을 제공하는것이다.

 

main() {
  final rectangle = Rectangle(2, 5);
}

class Rectangle {
  final int width;
  final int height;
  final int area;
  
  The area of the rectangle uses the `width` and `height`
  variables, but cannot be done outside of the constructor
  because the class doesn't know what the width and height
  are equal to until an instance is created.
  Rectangle(this.width, this.height) 
    : area = width * height {
      print(area);
    }
}

를 실행하면 20이 출력된다. 이는 생성자가 생성되고 실행되기전 width = 2, height = 5임을 통해 area = 20을 할당시킬수 있는 덕분이다.