ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • copyWith 함수
    flutter 2021. 12. 7. 15:08

    사용예제는 이러하다

     

    final ThemeData theme = Theme.of(context);
    Text("등록",
        style: theme.textTheme.subtitle1!.copyWith(color: AppColors.primary))

     

     

    https://developer.school/tutorials/dart-flutter-what-does-copywith-do

     

    https://developer.school/tutorials/dart-flutter-what-does-copywith-do

     

    developer.school

     

    블로그를 참조하면..

     

     

    -->

    불변성을 사용하면 더 이상 개체에 대한 내부 변경 사항을 추적할 필요가 없으므로 추론하기 쉬운 코드를 만들 수 있습니다. 이것은 원격 소스에서 오는 데이터로 작업할 때 특히 유용합니다.

    copyWith원본과 속성이 같지만 일부 값이 변경된 새 개체를 만드는 데 사용 합니다. 그런 다음 이러한 기술을 Freezed 와 함께 적용 하여 변경할 수 없는 구조를 만들고 작업하는 프로세스를 더 쉽게 만들 수 있습니다.

     

     

    라고한다.

    그러하다.

     

     

     

     

     

    다른 데이터 객체에도 적용가능하다.

     

    위의 블로그를 복붙하자면..

     

    자신의 copyWith기능 을 만드는 방법

    copyWith변경하려는 값을 가져오고 새 값으로 새 객체를 반환 하여 고유한 함수를 만들 수 있습니다 .

    다음은 Product클래스 가 있는 예입니다 .

    class Product {
      final String id;
      final String name;
      final Color color;
    
      Product({this.id, this.color, this.name});
    
      Product copyWith({String id, String name, Color color}) => Product(
            id: id ?? this.id,
            name: name ?? this.name,
            color: color ?? this.color,
          );
    }
    

    copyWith함수 내에서 id, name및 와 같은 잠재적 재정의  color받습니다. 그런 다음  Product중 하나를 사용하여  current값 을 반환 하거나 해당 값을 전달된 값으로 바꿉니다.

    이것을 사용하여 우리가 판매하는 식당 테이블 목록을 표시할 수 있습니다. 둘 다 같은 이름을 가지고 있지만, 다른이 id와 color:

    class _HomePageState extends State<HomePage> {
      List<Product> products = [];
    
      @override
      void initState() {
        super.initState();
    
        Product sixSeaterDiningTableBrown = Product(
          id: "0",
          name: "6 Seater Dining Table",
          color: Colors.brown,
        );
    
        Product sixSeaterDiningTableBlack =
            sixSeaterDiningTableBrown.copyWith(color: Colors.black, id: "1");
    
        products.add(sixSeaterDiningTableBrown);
        products.add(sixSeaterDiningTableBlack);
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Hello, copyWith!"),
          ),
          body: ListView(
              children: products
                  .map((Product product) => ListTile(
                        trailing: Container(
                          width: 14,
                          height: 14,
                          color: product.color,
                        ),
                        title: Text(product.name),
                        subtitle: Text(product.id),
                      ),
                    )
                  .toList(),
                ),
        );
      }
    }
    

    이 경우 에 두 개의 항목이 표시됩니다 ListView. 첫 번째 항목은 sixSeaterDiningTableBrown이고 두 번째 항목은 sixSeaterDiningTableBlack입니다.

    id와는 color다른,하지만은 name동일합니다. 직접 복사하는 대신 immutable copyWith함수를 사용하여 생성 sixSeaterDiningTableBlack했습니다 sixSeaterDiningTableBrown.

    이것은 작은 예이지만 이 패턴을 사용하여 더 큰 응용 프로그램에서 데이터 작업을 수행하는 방법을 볼 수 있습니다.

     

     

     

     

    ----> 라고한다.

     

    그리고 비슷하게 

    apply 함수가있다

    사용예는..

     

    Text(
      title,
      style: theme.textTheme.subtitle2!
          .apply(color: AppColors.text50),
    ),

     

     

     

    copyWith와 좀 비슷한데..스택오버플로우를 찾아보니

     

     

    답변1

    apply() 지정된 속성을 바꾸거나 변경하는 텍스트 스타일의 복사본을 만듭니다.

    copyWith() 텍스트 스타일의 복사본을 생성하지만 주어진 필드는 새로운 값으로 대체됩니다.

     

    답변2

    주요 차이점은 소스의 매개 apply()변수를 확장 하기 위해 여러 매개변수를 제공 한다는 것 TextStyle입니다.

    예를 들어, copyWith(fontSize: 14)동안 명시 적으로 글꼴 크기를 설정할 수 있습니다 apply(fontSizeFactor: 1.6)당신이 할 수 확장 소스의 글꼴 크기 에 의해 (명시 적 있습니다 사용자 정의 요소 fontSize매개 변수가 존재하지 않습니다 apply()).

     

    라는 답변이 있음..

     

     

     

    스택오버플로우 참조

    https://stackoverflow.com/questions/68357047/flutter-apply-or-copywith-method

     

     

     

     

    기타 copywith 관련

    https://stackoverflow.com/questions/62372580/what-is-copywith-and-how-can-i-use-it-in-flutter-and-what-is-its-use-case

     

     

Designed by Tistory.