Flutter 코드 확장

Flutter 코드 확장



Flutter의 중첩된 위젯 구조에 대한 대안을 찾고 계십니까? 복잡한 위젯을 다른 위젯으로 추출하는 것이 좋은 솔루션이 될 수 있습니다. 다른 솔루션이 있거나 두 솔루션이 함께 작동할 수도 있습니다.

이를 위해 Dart 2.7에 도입된 Extension이라는 Dart 기능의 힘을 활용할 수 있습니다.

그렇다면 Dart에서 확장이란 무엇입니까?



확장은 dart 데이터 유형에 추가 기능을 추가하는 방법입니다.
String 데이터 유형을 예로 들어 보겠습니다.


String myString = 'Hello world!'

// here toUpperCase() is a method which can
// be applied to a String data type.
print(myString.toUpperCase())

마찬가지로 데이터 유형에 고유한 메서드를 추가할 수 있습니다.

다음 구문을 사용하여 데이터 유형에 대한 확장을 만들 수 있습니다.

extension StringExtend on String {
    // define methods here
}

그리고 이 안에 메서드를 정의할 수 있습니다.


extension StringExtend on String {
  count(String a) {
    int count = 0;
    for (int i = 0; i < this.length; i++) {
      if (this[i] == a) count = count + 1;
    }
    return count;
  }
}


참고: 확장 메서드가 호출된 변수는 이 키워드를 사용하여 메서드 내에서 액세스할 수 있습니다.

여기에서 count()를 매개변수로 사용하고 호출된 문자열에서 이 문자열의 발생 횟수를 반환하는 간단한 메서드String를 정의했습니다.

전체 코드는 다음과 같습니다.


extension StringExtend on String {
  count(String a) {
    int count = 0;
    for (int i = 0; i < this.length; i++) {
      if (this[i] == a) count = count + 1;
    }
    return count;
  }
}

void main() {
  String myText = 'This is my string';

  // prints 3 in the console
  print(myText.count('i'));
}


마찬가지로 확장에 다른 메서드를 추가할 수 있습니다.

extension StringExtend on String {
  count(String a) {
    int count = 0;
    for (int i = 0; i < this.length; i++) {
      if (this[i] == a) count = count + 1;
    }
    return count;
  }

  makeFunky() {
    String result = '';
    for (int i = 0; i < this.length; i++) {
      final text = i % 2 == 0 ? this[i].toLowerCase() : this[i].toUpperCase();
      result = result + text;
    }
    return result;
  }
}

void main() {
  String myText = 'This is my string';

  // prints 3 in the console
  print(myText.count('i'));
  // prints iHiS Is mY StTiNg
  print(myText.makeFunky());
}


이제 extension 구문을 잘 이해했으며 FLutter에서 이것을 구현하는 방법을 살펴보겠습니다.

이후 모든 것이 Widget 펄럭입니다. Widget 데이터 유형에 확장자를 추가할 수 있습니다. 또는 Widget 또는 Text() 와 같은 특정 Container() .
Text() 위젯의 글꼴 크기를 변경하는 flutter 확장 프로그램을 만들어 보겠습니다.

확장이 없으면 코드는 다음과 같이 보일 것입니다.

build() {
    return Text(
       'Hello world!',
       style: TextStyle(
         fontSize: 24,
        ),
    );
}

확장 포함

// first define the extension
extension TextModifier on Text {
  Text fontSize(double fontSize) {
    // if the Text() widget doesn't already have an style
    // just apply the fontSize
    if (this.style == null) {
      return Text(
        this.data,
        style: TextStyle(fontSize: fontSize),
      );
    }

    // if there is already an style applied to it
    // extend that style with fontSize
    return Text(
      this.data,
      style: this.style.copyWith(fontSize: fontSize),
    );
  }
}


// actual code implementation

build() {
    return Text('Hello World!').fontSize(24);
}

코드가 얼마나 가독성이 좋은지 확인하십시오.
예, 확장을 정의하기 위한 더 많은 상용구가 있지만 그것은 한 번만 수행해야 하는 것이며 Text() 위젯을 사용하는 동안 나중에 과일만 사용해야 합니다.

마찬가지로 확장에 메서드를 추가하여 메서드를 연결할 수 있습니다.

// define extension

extension TextModifier on Text {
  Text color(Color color) {
    if (this.style == null) {
      return Text(
        this.data,
        style: TextStyle(color: color),
      );
    }
    return Text(
      this.data,
      style: this.style.copyWith(color: color),
    );
  }

  Text fontSize(double fontSize) {
    if (this.style == null) {
      return Text(
        this.data,
        style: TextStyle(fontSize: fontSize),
      );
    }

    return Text(
      this.data,
      style: this.style.copyWith(fontSize: fontSize),
    );
  }
}

// use the goodness
build() {
    return Text('Hello World!')
    .fontSize(24)
    .color(Colors.green);
}


코드가 얼마나 읽기 쉬운지 확인하십시오.

더 많은 예를 보자

확장 정의

extension TextModifier on Text {
  Text color(Color color) {
    if (this.style == null) {
      return Text(
        this.data,
        style: TextStyle(color: color),
      );
    }
    return Text(
      this.data,
      style: this.style.copyWith(color: color),
    );
  }

  Text fontSize(double fontSize) {
    if (this.style == null) {
      return Text(
        this.data,
        style: TextStyle(fontSize: fontSize),
      );
    }

    return Text(
      this.data,
      style: this.style.copyWith(fontSize: fontSize),
    );
  }
}

extension WidgetModifier on Widget {
  Widget padding({horizontal, vertical}) {
    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: horizontal,
        vertical: vertical,
      ),
      child: this,
    );
  }

  Widget background(Color color) {
    return DecoratedBox(
      decoration: BoxDecoration(
        color: color,
      ),
      child: this,
    );
  }
}

확장 없음

build(BuildContext context) {
    return Container(
      color: Colors.purple,
      padding: const EdgeInsets.symmetric(
        horizontal: 10,
        vertical: 20,
      ),
      child: Container(
        color: Colors.lightBlue,
        child: Text(
          'Hello, World!',
          style: TextStyle(
              color: Colors.purple,
              fontSize: 50.0,
            ),
        ),
      ),
    );
  }


확장 포함

build(BuildContext context) {
    return Text('Hello, World!')
        .color(Colors.purple)
        .fontSize(50.0)
        .background(Colors.lightBlue)
        .padding(horizontal: 10, vertical: 20)
        .background(Colors.purple)
  }


결론



이 블로그에서 가르치는 내용을 사용하는 예제 앱은 Github에서 찾을 수 있습니다.

간단한 위젯을 반복하기 위한 상용구 코드를 줄이기 위해 플러터에서 Dart 확장을 사용할 수 있습니다. 위젯이 더 복잡한 경우 별도의 위젯으로 추출하는 것이 좋습니다.

Flutter 코드에서 확장을 사용하는 것에 대한 귀하의 생각을 듣고 싶습니다. 당신이 이것을 좋아한다면 당신은 다음의 멋진 UI 프레임워크VelocityX를 좋아할 것입니다.

다음에 다루길 원하는 내용을 알려주세요. 그동안 저를 팔로우하세요.

해피코딩

좋은 웹페이지 즐겨찾기