회원가입 버튼 함수

UserController.to.join(_username.text.trim(), _email.text.trim(), _password.text.trim());

UserController

Future<void> join(String username, String email, String password) async {
    String result = await _userRepository.join(username, email, password);
    if (result == "success") {
      print("success");
    } else if (result == "user-not-found") {
      print('No user found for that email.');
    } else if (result == "wrong-password") {
      print('Wrong password provided for that user.');
    } else {
      print(result);
    }
  }

JoinReqDto

class JoinReqDto {
  final String? username;
  final String? email;
  final String? password;

  JoinReqDto(this.username, this.email, this.password);
  Map<String, dynamic> toJson() => {
        "username": username,
        "email": email,
        "password": password,
      };
}

UserRepository

Future<String> join(String username, String email, String password) async {
    JoinReqDto dto = JoinReqDto(username, email, password);
    try {
      UserCredential userCredential = await _userProvider.join(dto);
      UserModel _newUser = UserModel(
        uid: userCredential.user!.uid,
        email: email,
        name: username,
        photoUrl: "photoUrl",
      );
      await _userProvider.joinDetail(_newUser);
      return "success";
    } on FirebaseAuthException catch (e) {
      return e.code;
    }
  }

UserProvider

// firebase auth 등록
Future<UserCredential> join(JoinReqDto dto) async =>
      await auth.createUserWithEmailAndPassword(
          email: dto.email.toString(), password: dto.password.toString());
// firebase storage 등록
Future<void> joinDetail(UserModel user) async =>
      await firebaseFirestore.doc('/users/${user.uid}').set(user.toJson());

Git Commit

https://github.com/mugon-dev/flutter_firebase_blog/commit/d5a51d681816c3759436585345cbf2d4fc39dab4

 

email, password, username 회원가입, 로그인, 로그아웃 구현 및 클라우드 저장 · mugon-dev/flutter_firebase_blo

Permalink This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. Browse files email, password, username 회원가입, 로그인, 로그아웃 구현 및 클라우드 저장 Loading branch informati

github.com

 

728x90

Main

firebase 초기화 중 Splash()를 먼저 보여주고 AuthController에서 로그인 상태에 따라 페이지 이동

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initialization.then((value) {
    Get.put(AuthController());
  });
  runApp(App());
}

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      home: Splash(),
    );
  }
}

class Splash extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: CircularProgressIndicator()),
    );
  }
}

 

AuthController

onReady 함수 내에서 로그인 상태를 확인, 그에 따라 페이지 이동

class AuthController extends GetxController {
  static AuthController get to => Get.find();
  Rxn<User> firebaseUser = Rxn<User>();
  Rxn<UserModel> firestoreUser = Rxn<UserModel>();
  RxBool isLoggedIn = false.obs;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    //run every time auth state changes
    ever(firebaseUser, handleAuthChanged);
    firebaseUser.bindStream(user);
  }

  handleAuthChanged(_firebaseUser) async {
    //get user data from firestore
    if (_firebaseUser?.uid != null) {
      firestoreUser.bindStream(streamFirestoreUser());
    }
    if (_firebaseUser == null) {
      Get.offAll(() => LoginPage());
    } else {
      Get.offAll(() => HomePage());
    }
  }

  //Streams the firestore user from the firestore collection
  Stream<UserModel> streamFirestoreUser() {
    print('streamFirestoreUser()');

    return firebaseFirestore
        .doc('/users/${firebaseUser.value!.uid}')
        .snapshots()
        .map((snapshot) => UserModel.fromMap(snapshot.data()!));
  }

  // Sign out
  Future<void> signOut() {
    return auth.signOut();
  }
}

Git commit

https://github.com/mugon-dev/flutter_firebase_blog/commit/d5a51d681816c3759436585345cbf2d4fc39dab4

 

email, password, username 회원가입, 로그인, 로그아웃 구현 및 클라우드 저장 · mugon-dev/flutter_firebase_blo

Permalink This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. Browse files email, password, username 회원가입, 로그인, 로그아웃 구현 및 클라우드 저장 Loading branch informati

github.com

 

728x90

Installation

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.4.0

Android

Project Setting

Installing Firebase configuration File

android/build.gradle

google - service 버전 확인

buildscript {
  dependencies {
    // ... other dependencies
    classpath 'com.google.gms:google-services:4.3.8'
  }
}

/android/app/build.gradle

apply plugin: 'com.google.gms.google-services'

minSdkVersion 최소 16

호환성 해결

/android/app/build.gradle

android {
    defaultConfig {
        // ...
        minSdkVersion 16
        targetSdkVersion 28
        multiDexEnabled true
    }
}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

Enabling use of Firebase Emulator Suite

android/app/src/debug/AndroidManifest.xml

기존 application android태그안에 usesCleartextTraffic="true" 추가
http 주소 사용가능

<application android:usesCleartextTraffic="true">
  <!-- possibly other elements -->
</application>

Firebase console에서 앱 추가

android 앱에 firebase 추가

앱 등록 - Android 패키지 이름

android/app/build.gradle 의 applicationId

앱 등록 - 디버그 서명 인증서 SHA (Mac version)

터미널
비밀번호 : android

keytool -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

아래의 인증서 지문 복사 , 붙여넣기

구성파일 다운로드

파일은 다운받아 android/app 위치에 저장

FirebaseSDK 추가

android/build.gradle

buildscript {
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
  }
  dependencies {
    ...
    // Add this line
    classpath 'com.google.gms:google-services:4.3.8'
  }
}

allprojects {
  ...
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
    ...
  }
}

android/app/build.gradle

apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'

dependencies {
  // Import the Firebase BoM
  implementation platform('com.google.firebase:firebase-bom:28.2.0')

  // Add the dependency for the Firebase SDK for Google Analytics
  // When using the BoM, don't specify versions in Firebase dependencies
  implementation 'com.google.firebase:firebase-analytics-ktx'

  // Add the dependencies for any other desired Firebase products
  // https://firebase.google.com/docs/android/setup#available-libraries
}

IOS

Firebase console에서 앱 추가

ios 폴더 우클릭으로 xcode에서 열기

Runner 클릭

bundle identifier 부분이 ios 번들 id

대문자가 들어가면 안되니 - 소문자로 변경

com.example.firebaseSetting → com.example.firebase-setting

구성파일 추가

Runner/Runner 위치에 추가

추가한 파일의 client id를 복사해서

Runner / info 의 URL types의 URL schemes에 추가

Enabling use of Firebase Emulator Suite

ios/Runner/Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsLocalNetworking</key>
    <true/>
</dict>

pop error

ios 폴더 위치에서 pod install

ios version error

ios deployment target version 변경

Git commit

https://github.com/mugon-dev/flutter_firebase_blog/commit/74b44de7d0320a0085f432b160cfe0c7e42865b3

 

firebase android, ios setting · mugon-dev/flutter_firebase_blog@74b44de

Permalink This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. Browse files firebase android, ios setting Loading branch information Showing 13 changed files with 244 additions and 113 deletions.

github.com

 

728x90

Github

https://github.com/mugon-dev/flutter_firebase_blog

 

GitHub - mugon-dev/flutter_firebase_blog

Contribute to mugon-dev/flutter_firebase_blog development by creating an account on GitHub.

github.com

프로젝트 구조 참고

https://www.youtube.com/playlist?list=PL93mKxaRDidESjm_xR9BEKj5VJQMXy0tM 

 

플러터 GetX 상태관리

 

www.youtube.com

주의사항

공부 하면서 프로젝트를 진행하기 때문에 쓸모없는 코드가 존재하거나, 필요이상으로 복잡하거나 난잡할 수도 있습니다.

728x90

+ Recent posts