flutter_flavor + flutter_flavorize를 사용하여 Flutter의 Flavor 설정

Flutter에서 각 환경에 따라 구축 설정을 전환하려면 Flavor를 설정해야 합니다.
Creating flavors for Flutter - Flutter
그런데 찾아보니 Flavor를 설정하기 위해서는 OS마다 수동으로 설정해야 하기 때문에 번거롭다.
  • [Fluter] Flavor 설정~build까지(Android 편)-Qita
  • 환경에 따라 구축 설정 - iOS 편을 Flutter로 전환합니다.모바일 응용 프로그램 개발에서 모든 환경에 따라 설정을 바꾸고 구축하며 발표하는 것은 거의 필수적이다🇯🇵 | Medium
  • 더 쉽게 Flavor를 설정할 수 있는지 조사해 아래 포장을 사용하면 가능하다.
  • flutter_flavor
  • flutter_flavorizr
  • 따라서 이 두 소프트웨어 패키지를 사용하여 Flavor를 설정하는 방법을 총괄했습니다.

    각 패키지 설치

    pubspec.yaml에서 다음과 같다.
    pubspec.yaml
    dependencies:
      flutter_flavor: ^1.1.3
      flutter_flavorizr: ^1.0.9
    
    그런 다음 flutter pub get 명령을 실행합니다.

    flutter_flavorizr

    flutter_flavorizr는 OS별 Flavor 설정을 통합 관리하는 패키지입니다.따라서 모든 운영체제가 수동으로 설치해야 하는 번거로움을 없앨 수 있다.

    flutter_flavorize 준비 사용


    사용하기 위해flutter_flavorizr 아래 3개를 미리 준비해야 한다.
  • Ruby
  • Gem

  • Xcodeproj(RubyGems 경유)
  • Mac의 경우 RubyGem가 설치되어 있을 수 있지만 권한 문제로 사용할 수 없습니다gem install.
    따라서 설치RubyGem 시에는 rbenv를 권장합니다.
    설치 방법은 다음과 같은 내용을 참고하였다.
    gem install에서 permission 오류가 발생할 경우 대응하는 방법 - Qiita

    Flavor 설정


    Flavor를 설정하려면 아래와 같이pubspec을 수행합니다.Flavor를 정의하려면 yaml을 편집해야 합니다.
    pubspec.yaml
    # Flavorの設定
    flavorizr:
      app:
        android:
          flavorDimensions: "flavor-type"
        ios:
    
      flavors:
        local:
          app:
            name: "アプリ名(local)"
    
          android:
            applicationId: "com.example.testapp.local"
    
          ios:
            bundleId: "com.example.testapp.local"
    
        dev:
          app:
            name: "アプリ名(dev)"
    
          android:
            applicationId: "com.example.testapp.dev"
          ios:
            bundleId: "com.example.testapp.dev"
    
        prod:
          app:
            name: "アプリ名"
    
          android:
            applicationId: "com.example.testapp"
          ios:
            bundleId: "com.example.testapp"
    
    이름이 flavorizr인 새 키를 추가하고 정의appflavors 두 개의 하위 항목을 추가합니다.app 아래에서 각 OS의 고유한 구축 설정을 정의할 수 있습니다.
    주의해야 할 것은 flavorDimensions 공식에'required가짜'라는 기록이 있지만 굳이 뭘 쓰지 않으면 오류가 발생할 수 있다는 것이다.
    특별히 신경 쓰지 않으면 flavor-type라고 쓰면 문제없다.flavors 배열에서 Flavor의 이름을 정의할 수 있습니다.
    이번 예는 로컬과 dev,prod를 만드는 것이다.
    각 Flavor는 애플리케이션 이름, 애플리케이션 ID, 번들 ID를 지정해야 합니다.

    Flavor 설정 반영


    Flavor 설정이 완료되면 다음 명령을 실행하여 스크립트를 실행할 수 있습니다.
    flutter pub run flutter_flavorizr
    
    스크립트가 완성되면 Flavor에 사용되는 다양한 코드를 자동으로 생성하고 추가합니다.
    또한 각 플라보main-xxx.dartxxx마다 플라보어 이름이 자동으로 생성됩니다.

    동작 확인


    Android 또는 iOS의 실제 또는 에뮬레이터 등에 연결하여 다음 명령을 실행하여 애플리케이션을 시작합니다.
    예를 들어, local로 Flavor를 시작합니다.
    flutter run --flavor local -t lib/main-local.dart
    
    후 아래 화면을 시작합니다.

    iOS 에뮬레이터를 사용하여 부팅하면 다음 오류가 발생하여 부팅에 실패할 수 있습니다.
    Launching lib/main-local.dart on iPhone 12 Pro Max in debug mode...
    
    Running pod install...                                              4.3s
    Running Xcode build...
    Xcode build done.                                           25.6s
    Failed to build iOS app
    Error output from Xcode build:
    ↳
        2021-02-14 08:43:14.336 xcodebuild[4440:55848] [MT] PluginLoading: Required plug-in compatibility UUID 2F1A5FFF-BFEB-4498-B2AC-1296A7454F81 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/Unity4XC.xcplugin' not present in DVTPlugInCompatibilityUUIDs
        2021-02-14 08:43:14.336 xcodebuild[4440:55848] Failed to load plugin at: /Users/Hitoshi/Library/Application Support/Developer/Shared/Xcode/Plug-ins/Unity4XC.xcplugin, skipping.  Reason for failure: *** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]
        ** BUILD FAILED **
    
    
    Xcode's output:
    ↳
        diff: /Podfile.lock: No such file or directory
        diff: /Manifest.lock: No such file or directory
        error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
        note: Using new build system
        note: Building targets in parallel
        note: Planning build
        note: Constructing build description
        warning: Ignoring destination platform iOS and building against target platform iOS Simulator. If this target is intended to build for only iOS Simulator, configure its Supported Platforms build setting to remove iOS. If this target is intended to build for both iOS and iOS Simulator, set its Base SDK build setting to Latest iOS. (in target 'Toast' from project 'Pods')
        warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'Toast' from project 'Pods')
        warning: Ignoring destination platform iOS and building against target platform iOS Simulator. If this target is intended to build for only iOS Simulator, configure its Supported Platforms build setting to remove iOS. If this target is intended to build for both iOS and iOS Simulator, set its Base SDK build setting to Latest iOS. (in target 'flutter_secure_storage' from project 'Pods')
        warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'flutter_secure_storage' from project 'Pods')
        warning: Ignoring destination platform iOS and building against target platform iOS Simulator. If this target is intended to build for only iOS Simulator, configure its Supported Platforms build setting to remove iOS. If this target is intended to build for both iOS and iOS Simulator, set its Base SDK build setting to Latest iOS. (in target 'fluttertoast' from project 'Pods')
        warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'fluttertoast' from project 'Pods')
        warning: Ignoring destination platform iOS and building against target platform iOS Simulator. If this target is intended to build for only iOS Simulator, configure its Supported Platforms build setting to remove iOS. If this target is intended to build for both iOS and iOS Simulator, set its Base SDK build setting to Latest iOS. (in target 'Pods-Runner' from project 'Pods')
        warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'Pods-Runner' from project 'Pods')
        warning: Ignoring destination platform iOS and building against target platform iOS Simulator. If this target is intended to build for only iOS Simulator, configure its Supported Platforms build setting to remove iOS. If this target is intended to build for both iOS and iOS Simulator, set its Base SDK build setting to Latest iOS. (in target 'Runner' from project 'Runner')
        warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'Runner' from project 'Runner')
        warning: Capabilities for Signing & Capabilities may not function correctly because its entitlements use a placeholder team ID. To resolve this, select a development team in the Runner editor. (in target 'Runner' from project 'Runner')
        warning: Ignoring destination platform iOS and building against target platform iOS Simulator. If this target is intended to build for only iOS Simulator, configure its Supported Platforms build setting to remove iOS. If this target is intended to build for both iOS and iOS Simulator, set its Base SDK build setting to Latest iOS. (in target 'Flutter' from project 'Pods')
        warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'Flutter' from project 'Pods')
    
    Could not build the application for the simulator.
    Error launching application on iPhone 12 Pro Max.
    
    이때ios/Runner.xcodeproj는 Xcode 측면에서 열고 Update to recommended settings의 경고를 보내야 합니다. 해제하십시오.
    자세한 내용은 아래 사이트를 참조하였다.
    Could not build the application for the simulator. Error launching application on iPhone의 대응 - Qita

    flutter_flavor

    flutter_flavor는 각 Flavor를 통해 제목의 위치와 색상을 변경하거나 변수(API의 URL 등)를 설정할 수 있는 프로그램 라이브러리입니다.

    Flavor당 리소스 전환


    예를 들어 local 환경의 설정 예는 다음과 같다.
    main-local.dart
    void main() {
      FlavorConfig(
          name: "LOCAL",
          color: Colors.red,
          location: BannerLocation.bottomStart,
          variables: {
            "baseUrl": "https://local-testapp.com/api",
          });
      F.appFlavor = Flavor.LOCAL;
      runApp(App());
    }
    
    name, color, location는 각각 제목에 표시된 라벨 이름, 제목의 색깔, 제목의 위치이다.variables는 응용 프로그램 내부에서 사용하는 전역 변수이다.
    여기서 환경에 따라 API의 URL을 설정합니다.
    예를 들어 설정baseUrl을 통해 다음과 같이 호출하여 사용할 수 있다.
    // Flavorによって値が変化する
    var baseUrl = FlavorConfig.instance.variables["baseUrl"];
    
    또한 FlavorBanner를 사용하여 방금 설정한 제목을 표시합니다.
    app.dart
    class App extends StatelessWidget {
      
      Widget build(BuildContext context) {
        return (
          child: MaterialApp(
            title: F.title,
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: MyHomePage(),
          ),
        );
      }
    }
    
    FlavorBanner를 상위 부품으로, MaterialApp를 하위 부품으로 설정합니다.
    완료 후 다시 프로그램을 구축하고 시작하면 다음 화면을 시작합니다.

    총결산


    flutter_flavor + flutter_flavorizr를 사용하여 Flutter의 Flavor를 설정합니다.
    이러한 패키지를 사용하면 각 운영 체제의 수동 설정 문제를 줄일 수 있습니다.
    또한 pubspec.yaml를 통해 관리 설정을 통일하는 것도 장점이다.
    그러나dart코드 등은 자동으로 생성되기 때문에 이미 실현된 기존 프로젝트에 도입하는 것은 힘들다.

    좋은 웹페이지 즐겨찾기