Firebase 설치 방법 입니다.
1. iOS
제한 플랫폼 : iOS 10, macOS 10.12 이상
클라우드 메세징 ( Cloud Messaging ) 만
- Apple 개발자 계정의 Apple 푸시 알림 인증 키를 가져옵니다
- XCode의 App(앱) > Capabilities(기능)에서 푸시 알림을 사용 설정합니다.
설치 방법 :
1. Google 계정을 사용하여 Firebase에 로그인
2. Firebase Console의 프로젝트 개요 페이지 중앙에 있는 iOS+ 아이콘을 클릭하여 설정 워크플로를 시작
3. iOS 번들 ID 필드에 앱의 번들 ID를 입력
- XCode 프로젝트에서 이 번들 ID를 확인 ( General(일반) 탭 -> Bundle Identifier(번들 식별자) 값이 iOS 번들 ID(예: com.yourcompany.ios-app-name) )
4. 앱 등록
5. GoogleService-Info.plist 다운로드를 클릭하여 Firebase Apple 플랫폼 구성 파일(GoogleService-Info.plist)을 다운로드
6. Xcode를 사용하여 파일을 Flutter 앱의 Runner/Runner 디렉터리로 이동
7. Firebase Console 설정 워크플로로 돌아가서 다음을 클릭하여 나머지 단계를 건너뜀
- Flutter 앱의 루트 디렉터리에서 pubspec.yaml 파일 내 하기와 같이 작성
dependencies:
flutter:
sdk: flutter
# Check that you have this dependency (added in the previous step)
firebase_core: ^0.4.0+9
# Add the dependencies for the Firebase products you want to use in your app
# For example, to use Firebase Authentication and Cloud Firestore
firebase_auth: ^0.14.0+5
cloud_firestore: ^0.12.9+5
9. 구글 애널리틱스 사용 시 하기와 같이 추가로 작성
dependencies:
flutter:
sdk: flutter
# Check that you have this dependency (added in the previous step)
firebase_core: ^0.4.0+9
# Add the dependency for the FlutterFire plugin for Google Analytics
firebase_analytics: ^5.0.2
# Add the dependencies for any other Firebase products you want to use in your app
# For example, to use Firebase Authentication and Cloud Firestore
firebase_auth: ^0.14.0+5
cloud_firestore: ^0.12.9+5
10. flutter packages get을 실행
추가 정보는 하기 링크 참고
https://firebase.google.com/docs/flutter/setup?hl=ko&platform=ios#analytics-not-enabled
Flutter 앱에 Firebase 추가 | Firebase Documentation
의견 보내기 Flutter 앱에 Firebase 추가 plat_ios plat_android 이 가이드에 따라 Flutter 앱에 Firebase 제품을 추가하세요. 참고: Firebase는 Flutter와 같은 프레임워크를 최선의 노력으로 지원합니다. 이러한 제
firebase.google.com
사용법
firebase_config.dart
import 'dart:developer';
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
class DefaultFirebaseConfig {
static FirebaseOptions? get platformOptions {
if (kIsWeb) {
// Web
return const FirebaseOptions(
apiKey: 'AIzaSyAgUhHU8wSJgO5MVNy95tMT07NEjzMOfz0',
authDomain: 'react-native-firebase-testing.firebaseapp.com',
databaseURL: 'https://react-native-firebase-testing.firebaseio.com',
projectId: 'react-native-firebase-testing',
storageBucket: 'react-native-firebase-testing.appspot.com',
messagingSenderId: '448618578101',
appId: '1:448618578101:web:0b650370bb29e29cac3efc',
measurementId: 'G-F79DJ0VFGS',
);
} else if (Platform.isIOS || Platform.isMacOS) {
// iOS and MacOS
return const FirebaseOptions(
appId: '1:448618578101:ios:cc6c1dc7a65cc83c',
apiKey: 'AIzaSyAHAsf51D0A407EklG1bs-5wA7EbyfNFg0',
projectId: 'react-native-firebase-testing',
messagingSenderId: '448618578101',
iosBundleId: 'com.invertase.testing',
iosClientId:
'448618578101-28tsenal97nceuij1msj7iuqinv48t02.apps.googleusercontent.com',
androidClientId:
'448618578101-a9p7bj5jlakabp22fo3cbkj7nsmag24e.apps.googleusercontent.com',
databaseURL: 'https://react-native-firebase-testing.firebaseio.com',
storageBucket: 'react-native-firebase-testing.appspot.com',
);
} else {
// Android
log("Analytics Dart-only initializer doesn't work on Android, please make sure to add the config file.");
return null;
}
}
}
main.dart
class MyHomePage extends StatefulWidget {
MyHomePage({
Key? key,
required this.title,
required this.analytics,
required this.observer,
}) : super(key: key);
final String title;
final FirebaseAnalytics analytics;
final FirebaseAnalyticsObserver observer;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _message = '';
void setMessage(String message) {
setState(() {
_message = message;
});
}
Future<void> _sendAnalyticsEvent() async {
await widget.analytics.logEvent(
name: 'test_event',
parameters: <String, dynamic>{
'string': 'string',
'int': 42,
'long': 12345678910,
'double': 42.0,
// Only strings and numbers (ints & doubles) are supported for GA custom event parameters:
// https://developers.google.com/analytics/devguides/collection/analyticsjs/custom-dims-mets#overview
'bool': true.toString(),
'items': [itemCreator()]
},
);
setMessage('logEvent succeeded');
}
Future<void> _testSetUserId() async {
await widget.analytics.setUserId(id: 'some-user');
setMessage('setUserId succeeded');
}
Future<void> _testSetCurrentScreen() async {
await widget.analytics.setCurrentScreen(
screenName: 'Analytics Demo',
screenClassOverride: 'AnalyticsDemo',
);
setMessage('setCurrentScreen succeeded');
}
Future<void> _testSetAnalyticsCollectionEnabled() async {
await widget.analytics.setAnalyticsCollectionEnabled(false);
await widget.analytics.setAnalyticsCollectionEnabled(true);
setMessage('setAnalyticsCollectionEnabled succeeded');
}
Future<void> _testSetSessionTimeoutDuration() async {
await widget.analytics
.setSessionTimeoutDuration(const Duration(milliseconds: 20000));
setMessage('setSessionTimeoutDuration succeeded');
}
Future<void> _testSetUserProperty() async {
await widget.analytics.setUserProperty(name: 'regular', value: 'indeed');
setMessage('setUserProperty succeeded');
}
AnalyticsEventItem itemCreator() {
return AnalyticsEventItem(
affiliation: 'affil',
coupon: 'coup',
creativeName: 'creativeName',
creativeSlot: 'creativeSlot',
discount: 2.22,
index: 3,
itemBrand: 'itemBrand',
itemCategory: 'itemCategory',
itemCategory2: 'itemCategory2',
itemCategory3: 'itemCategory3',
itemCategory4: 'itemCategory4',
itemCategory5: 'itemCategory5',
itemId: 'itemId',
itemListId: 'itemListId',
itemListName: 'itemListName',
itemName: 'itemName',
itemVariant: 'itemVariant',
locationId: 'locationId',
price: 9.99,
currency: 'USD',
promotionId: 'promotionId',
promotionName: 'promotionName',
quantity: 1,
);
}
Future<void> _testAllEventTypes() async {
await widget.analytics.logAddPaymentInfo();
await widget.analytics.logAddToCart(
currency: 'USD',
value: 123,
items: [itemCreator(), itemCreator()],
);
await widget.analytics.logAddToWishlist();
await widget.analytics.logAppOpen();
await widget.analytics.logBeginCheckout(
value: 123,
currency: 'USD',
items: [itemCreator(), itemCreator()],
);
await widget.analytics.logCampaignDetails(
source: 'source',
medium: 'medium',
campaign: 'campaign',
term: 'term',
content: 'content',
aclid: 'aclid',
cp1: 'cp1',
);
await widget.analytics.logEarnVirtualCurrency(
virtualCurrencyName: 'bitcoin',
value: 345.66,
);
await widget.analytics.logGenerateLead(
currency: 'USD',
value: 123.45,
);
await widget.analytics.logJoinGroup(
groupId: 'test group id',
);
await widget.analytics.logLevelUp(
level: 5,
character: 'witch doctor',
);
await widget.analytics.logLogin(loginMethod: 'login');
await widget.analytics.logPostScore(
score: 1000000,
level: 70,
character: 'tiefling cleric',
);
await widget.analytics
.logPurchase(currency: 'USD', transactionId: 'transaction-id');
await widget.analytics.logSearch(
searchTerm: 'hotel',
numberOfNights: 2,
numberOfRooms: 1,
numberOfPassengers: 3,
origin: 'test origin',
destination: 'test destination',
startDate: '2015-09-14',
endDate: '2015-09-16',
travelClass: 'test travel class',
);
await widget.analytics.logSelectContent(
contentType: 'test content type',
itemId: 'test item id',
);
await widget.analytics.logSelectPromotion(
creativeName: 'promotion name',
creativeSlot: 'promotion slot',
items: [itemCreator()],
locationId: 'United States',
);
await widget.analytics.logSelectItem(
items: [itemCreator(), itemCreator()],
itemListName: 't-shirt',
itemListId: '1234',
);
await widget.analytics.logScreenView(
screenName: 'tabs-page',
);
await widget.analytics.logViewCart(
currency: 'USD',
value: 123,
items: [itemCreator(), itemCreator()],
);
await widget.analytics.logShare(
contentType: 'test content type',
itemId: 'test item id',
method: 'facebook',
);
await widget.analytics.logSignUp(
signUpMethod: 'test sign up method',
);
await widget.analytics.logSpendVirtualCurrency(
itemName: 'test item name',
virtualCurrencyName: 'bitcoin',
value: 34,
);
await widget.analytics.logViewPromotion(
creativeName: 'promotion name',
creativeSlot: 'promotion slot',
items: [itemCreator()],
locationId: 'United States',
promotionId: '1234',
promotionName: 'big sale',
);
await widget.analytics.logRefund(
currency: 'USD',
value: 123,
items: [itemCreator(), itemCreator()],
);
await widget.analytics.logTutorialBegin();
await widget.analytics.logTutorialComplete();
await widget.analytics.logUnlockAchievement(id: 'all Firebase API covered');
await widget.analytics.logViewItem(
currency: 'usd',
value: 1000,
items: [itemCreator()],
);
await widget.analytics.logViewItemList(
itemListId: 't-shirt-4321',
itemListName: 'green t-shirt',
items: [itemCreator()],
);
await widget.analytics.logViewSearchResults(
searchTerm: 'test search term',
);
setMessage('All standard events logged successfully');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: <Widget>[
MaterialButton(
onPressed: _sendAnalyticsEvent,
child: const Text('Test logEvent'),
),
MaterialButton(
onPressed: _testAllEventTypes,
child: const Text('Test standard event types'),
),
MaterialButton(
onPressed: _testSetUserId,
child: const Text('Test setUserId'),
),
MaterialButton(
onPressed: _testSetCurrentScreen,
child: const Text('Test setCurrentScreen'),
),
MaterialButton(
onPressed: _testSetAnalyticsCollectionEnabled,
child: const Text('Test setAnalyticsCollectionEnabled'),
),
MaterialButton(
onPressed: _testSetSessionTimeoutDuration,
child: const Text('Test setSessionTimeoutDuration'),
),
MaterialButton(
onPressed: _testSetUserProperty,
child: const Text('Test setUserProperty'),
),
Text(
_message,
style: const TextStyle(color: Color.fromARGB(255, 0, 155, 0)),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute<TabsPage>(
settings: const RouteSettings(name: TabsPage.routeName),
builder: (BuildContext context) {
return TabsPage(widget.observer);
},
),
);
},
child: const Icon(Icons.tab),
),
);
}
}
전체 예제 코드는 하기 링크에 있습니다.
https://github.com/FirebaseExtended/flutterfire
GitHub - FirebaseExtended/flutterfire: 🔥 A collection of Firebase plugins for Flutter apps.
🔥 A collection of Firebase plugins for Flutter apps. - GitHub - FirebaseExtended/flutterfire: 🔥 A collection of Firebase plugins for Flutter apps.
github.com
'Flutter(플러터) > Setting' 카테고리의 다른 글
Flutter Permission ( permission_handler ) (0) | 2022.01.14 |
---|---|
Flutter Flavor 빌드 환경 구성 (0) | 2022.01.03 |
댓글