Skip to content

Instantly share code, notes, and snippets.

@iamEtornam
Last active February 15, 2022 15:38
Show Gist options
  • Save iamEtornam/71262583a36cf720e8e6e2daab914acd to your computer and use it in GitHub Desktop.
Save iamEtornam/71262583a36cf720e8e6e2daab914acd to your computer and use it in GitHub Desktop.
a flutter controller with firebase auth, storage, firestore usage
```dart
import 'package:firebase_auth/firebase_auth.dart';
abstract class AuthController {
Future<bool> loginUser(String email, String password);
Future<bool> logout();
}
class AuthControllerImpl implements AuthController {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
String _message = '';
String get message => _message;
setMessage(String msg) {
_message = msg;
}
@override
Future<bool> loginUser(String email, String password) async {
try {
final userCredetials =
await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
if (userCredetials.user != null) {
setMessage('Login Successful');
return true;
}
return false;
} catch (e) {
setMessage(e.toString());
return false;
}
}
@override
Future<bool> logout() async {
await _firebaseAuth.signOut();
return true;
}
}
import 'dart:io';
import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
abstract class UploadController {
Future<String?> uploadFile(File file, String folderName);
Future<bool> addPost(String url, String post);
}
class UploadControllerImpl implements UploadController {
final FirebaseStorage _storage = FirebaseStorage.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final FirebaseAuth _auth = FirebaseAuth.instance;
@override
Future<String?> uploadFile(File file, String folderName) async {
try {
final randomNumber = Random().nextInt(100000);
final Reference ref = _storage.ref().child(folderName).child('$randomNumber.jpg');
final UploadTask _uploadTask = ref.putFile(file);
final TaskSnapshot downloadUri = await Future.value(_uploadTask);
final String downloadUrl = (await downloadUri.ref.getDownloadURL());
return downloadUrl;
} catch (e) {
print(e);
return null;
}
}
@override
Future<bool> addPost(String url, String post) async {
try {
await _firestore.collection('posts').add({
'url': url,
'post': post,
'date': DateTime.now().toIso8601String(),
'user_id': _auth.currentUser!.uid
});
return true;
} catch (e) {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment