Flutter 에서 상수형 변수를 선언 하는 방법을 알아봅시다.
내가 모바일 애플리케이션을 작성하고 있다고 가정하면 로컬 스토리지에 사용자 기본 설정을 저장합니다.
로컬 스토리지의 각 값에는 키가 있어야 합니다(예: save_user_id: true, save_user_id는 키이고 true는 값임).
키를 상수로 정의합니다.
1. 일반 변수 타입
const String LocalStorageKeySaveUserId = 'save_user_id';
const String LocalStorageKeyUserId = 'user_id';
const String LocalStorageKeyLanguage = 'language';
const String LocalStorageKeyThemeMode = 'theme_mode';
const String LocalStorageKeyEnablePushNotification = 'enable_push_notification';
이것은 가장 일반적인 방식이지만 이름들은 너무 길고 우아하지 않습니다. 좀더 다듬어 봅시다.
2. 클래스 속성
class LocalStorageKey {
// add a private constructor to prevent this class being instantiated
// e.g. invoke `LocalStorageKey()` accidentally
LocalStorageKey._();
// the properties are static so that we can use them without a class instance
// e.g. can be retrieved by `LocalStorageKey.saveUserId`.
static const String saveUserId = 'save_user_id';
static const String userId = 'user_id';
static const String language = 'language';
static const String themeMode = 'theme_mode';
static const String enablePushNotification = 'enable_push_notification';
}
클래스 내부에서 각 상수를 선언했습니다. 하지만 String이나 int 같은 원시적인 타입으로는 부족할 때가 있어요. 다음과 같은 사용자 정의 상수 클래스를 정의할 수 있습니다
3. 커스텀 클래스
import 'package:flutter/foundation.dart';
class Currency {
final String name;
final String abbreviation;
final String symbol;
// use private constructor so that we can only create
// instances inside the class;
// the `const` keyword of constructor makes every instance
// initialized with the same parameters the same copy,
// so that we can compare them by `==` or `switch` statements
const Currency._({
@required this.name,
@required this.abbreviation,
@required this.symbol,
});
static const Currency usd = Currency._(
name: 'United States dollar',
abbreviation: 'USD',
symbol: '\$',
);
static const Currency gbp = Currency._(
name: 'Great British Pound',
abbreviation: 'GBP',
symbol: '£',
);
static const Currency jpy = Currency._(
name: 'Japanese Yen',
abbreviation: 'JPY',
symbol: '¥',
);
// put the values into an array so that we can iterate amoung them
static const List<Currency> values = [usd, gbp, jpy];
}
이것은 사용자 정의 상수 클래스 내에서 여러 정보를 캡슐화할 수 있는 방법입니다. == 연산자 또는 스위치 문을 사용하여 값을 비교할 수 있도록 상수 생성자를 사용했습니다.
끝
[Flutter] http 사용시에 리턴되는 한글 값이 깨질경우 해결 (0) | 2023.02.20 |
---|---|
[Flutter] 외부 API에서 데이터 가져오기 (0) | 2023.02.18 |
댓글 영역