Flutter Firebase - Android
Firebase 설치 방법 입니다.
1. iOS
제한 플랫폼 : API 수준 19 이상(KitKat), Android 4.4 이상
설치 방법 :
1. Google 계정을 사용하여 Firebase에 로그인
2. Firebase Console의 프로젝트 개요 페이지 중앙에 있는 Android 아이콘을 클릭하여 설정 워크플로를 시작
3. Android 패키지 이름 필드에 앱의 패키지 이름을 입력
- 모듈(앱 수준) Gradle 파일(일반적으로 app/build.gradle)에서 이 패키지 이름(패키지 이름 예시: com.yourcompany.yourproject)
4. 앱 등록
5. GoogleService-Info.plist 다운로드를 클릭하여 Firebase Apple 플랫폼 구성 파일(GoogleService-Info.plist)을 다운로드
6. Flutter 앱의 android/app 디렉터리로 이동
7. Android 앱에서 Firebase 서비스를 사용할 수 있도록 다음과 같이 google-services 플러그인을 Gradle 파일에 추가
- 루트 수준(프로젝트 수준) Gradle 파일(android/build.gradle)에서 Google 서비스 Gradle 플러그인을 포함하는 규칙을 추가합니다. Google의 Maven 저장소도 있는지 확인
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
// ...
dependencies {
// ...
// Add the following line:
classpath 'com.google.gms:google-services:4.3.10' // Google Services plugin
}
}
allprojects {
// ...
repositories {
// Check that you have following line (if not, add it):
google() // Google's Maven repository
// ...
}
}
- 모듈(앱 수준) Gradle 파일(일반적으로 android/app/build.gradle)에서 Google 서비스 Gradle 플러그인을 적용
// Add the following line:
apply plugin: 'com.google.gms.google-services' // Google Services plugin
android {
// ...
}
// ...
8. 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