Google이 만든 BaaS.
curl -sL https://firebase.tools | bash
위 코드를 입력해 cli를 설치한다.
컴터 비번 입력해야함.
firebase login
위 코드를 입력하면 구글 로그인을 하도록 창이 뜬다. 로그인에 성공하면 아래와 같은 화면을 볼 수 있음.
firebase projects:list
내가 현재 어떤 프로젝트를 가지고있는지도 볼 수 있다.
dart pub global activate flutterfire_cli
flutterfire configure --project={프로젝트명}
프로젝트 내에서 위 명령을 입력해야한다.
flutterfire configure --project=sfac-test-1114f
export PATH="$PATH":"$HOME/.pub-cache/bin"
이 명령어를 입력한 후에 flutterfire를 실행한다. 지금 .zshrc로 설정된 PATH가 따로 있어서 못찾는 듯. 이 방법은 임시조치라서 환경변수에 추가를 해 주는 게 좋겠다.
firebase_core
필수!cloud_firestore
선택파이어베이스가 연동이 되면 lib폴더에 firebase 관련 파일이 하나 생긴다. 절대 건들지 말라고 함.
main.dart에서 void main 부분에 Firebase를 호출한다.
이때 WidgetsFlutterBinding.ensureInitialized()
이부분을 추가해서 렌더링 전에 초기화하도록 한다. 그리고 비동기로 수정한다.
void main() async { //main 비동기로 수정
runApp(const MyApp());
WidgetsFlutterBinding.ensureInitialized(); //초기화
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
}
Tip
파이어베이스는 싱글톤 방식임
어떤 페이지에서 호출해도 동일한 인스턴스가 나온다.
store 위치는 서울로 한다.
데이터를 만들어놓을 수 있다.
FirebaseFireStore.instance.collection(컬렉션명).get();
FirebaseFireStore.instance.collection(컬렉션명).doc(Id).get();
FirebaseFireStore.instance.collection(컬렉션명).where(키, isEqualTo: 값);
List items = [];
var instance = FirebaseFirestore.instance;
readFromCloudFireStore() async {
var res = await instance.collection('/memo').get();
items = res.docs.map((e) => e.data()).toList();
setState(() {});
}
readDocument(String docId) async {
var res = await instance.collection('/memo').doc(docId).get();
print(res.data());
setState(() {});
}
readFinishedDoc() async {
var res = await instance
.collection('memo')
.where('isFinished', isEqualTo: true)
.get();
print(res.docs);
}
map형태로 데이터를 전달한다.
instance.collection(컬렉션명).add({'key': value, 'key2': value})
FirebaseFirestore.instance.collection(컬렉션명).doc(지정이름).set({'key': value})
createDoc(String title) async {
var res = await instance
.collection('memo')
.add({'title': title, 'isFinished': false});
}
createDocById(String title, String id) async {
var res = await instance
.collection('memo')
.doc(id)
.set({'title': title, 'isFinished': false});
}
FirebaseFirestore.instance.collection(컬렉션명).doc(지정이름).update({'key': value,});
updateDoc(String id, Map<String, dynamic> data) async {
var res = await instance.collection('memo').doc(id).update(data);
}
FirebaseFirestore.instance.collection(컬렉션명).doc(지정이름).delete();
deleteDoc(String id) async {
instance.collection('memo').doc(id).delete();
}
void initState() {
super.initState();
FirebaseAuth.instance.authStateChanges().listen((user) {
if (user != null) {
print('회원가입 or 유저 입장');
return;
}
print('회원가입 or 로그인 필요');
});
}
_handleSignupButton() {
FirebaseAuth.instance.createUserWithEmailAndPassword(
email: 'email@test.test',
password: '12341234',
),
}
FirebaseAuth.instance.signOut();
FirebaseAuth.instance.signInWithEmailAndPassword(
email:,
password:,
);
이 코드 복붙
import 'package:google_sign_in/google_sign_in.dart';
Future<UserCredential> signInWithGoogle() async {
// Trigger the authentication flow
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
// Obtain the auth details from the request
final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication;
// Create a new credential
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth?.accessToken,
idToken: googleAuth?.idToken,
);
// Once signed in, return the UserCredential
return await FirebaseAuth.instance.signInWithCredential(credential);
}
Profile 컬렉션 > userId 문서ID > MBTI, BloodType, Info..
DropdownButton에 초기값(현재값)을 줄 수 있다.
fetchProfile 한번 더 실행시키면 됨.
reference라는 참조방식. (폴더 경로)
final storageRef = FirebaseStorage.instance.ref();
경로를 먼저 설정한 뒤 저장이 가능해진다.
purFile 메서드를 사용한다.
final storageRef = FirebaseStorage.instance.ref('images/mountains.jpg');
await storageRef.putData(data);
파일 다운로드는 url로 처리할 수 있다.(안그런 경우도 있음)
final storageRef = FirebaseStorage.instance.ref('images/mountains.jpg');
var fileUrl = await storageRef.getDownloadUrl();
dart:io
에 있는 File을 이용해 XFile 타입을 File로 바꿔준다./images/uid
가 들어가야 함.
관련 android 문서
아래 코드를 'android/app/build.gradle' 에 추가한다.
android {
defaultConfig {
multiDexEnabled true
}
...
}
dependencies {
def multidex_version = "2.0.1"
implementation "androidx.multidex:multidex:$multidex_version"
}
Error output from CocoaPods:
↳
[!] Automatically assigning platform `iOS` with version `11.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.
Error running pod install
Error launching application on iPhone 14 Pro Max.
이런 에러가 난다.
# Uncomment this line to define a global platform for your project
platform :ios, '11.0'
[!] CocoaPods could not find compatible versions for pod "flutter_login_facebook":
In Podfile:
...
Error running pod install
Error launching application on iPhone 14 Pro Max.
ios/Podfile.lock 에 firebase의 버전을 확인한다.
pod 'FirebaseFirestore', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => '10.15.0'
이 부분 추가
target 'Runner' do
// 이 다음 줄이 추가됨 (중요!! 제일 뒤에 버전이 있음. 내 버전으로 바꿀 것)
pod 'FirebaseFirestore', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => '10.15.0'
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
Lexical or Preprocessor Issue (Xcode): 'PigeonParser.h' file not found
dependencies:
cloud_firestore: ^4.10.0
cupertino_icons: ^1.0.2
firebase_auth: ^4.11.0
firebase_core: ^2.18.0
firebase_storage: ^11.3.0
flutter:
sdk: flutter
get: ^4.6.6
flutter_login_facebook: ^1.8.0
dependencies:
cloud_firestore: 4.9.2
cupertino_icons: ^1.0.2
firebase_auth: 4.10.0
firebase_core: 2.16.0
firebase_storage: 11.2.7
flutter:
sdk: flutter
get: ^4.6.6
flutter_login_facebook: ^1.8.0
그리고 flutter clean을 해줌.
아래 파일들도 삭제하고 다시 빌드한다.
$ flutter clean
$ rm -Rf ios/Pods
$ rm -Rf ios/.symlinks
$ rm -Rf ios/Flutter/Flutter.framework
$ rm -Rf ios/Flutter/Flutter.podspec
$ rm ios/Podfile
하.... 열리질 않는다. 일단 포기