Skip to content

Instantly share code, notes, and snippets.

@iamEtornam
Created November 19, 2019 11:06
Show Gist options
  • Save iamEtornam/b2139e5edf2e93370b25e0fac44c9950 to your computer and use it in GitHub Desktop.
Save iamEtornam/b2139e5edf2e93370b25e0fac44c9950 to your computer and use it in GitHub Desktop.
using Provider for Authentication in Flutter
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:meler/repositories/user.repository.dart';
class LoginModel with ChangeNotifier {
TextEditingController _emailCtrl = TextEditingController();
TextEditingController _passwordCtrl = TextEditingController();
bool _isLoading = false;
String _errorMessage = "";
// Getters
TextEditingController get emailCtrl => _emailCtrl;
TextEditingController get passwordCtrl => _passwordCtrl;
bool get isLoading => _isLoading;
String get errorMessage => _errorMessage;
UserRepository _userRepository = UserRepository();
PersistData _localStorageService = PersistData();
pageIsLoading(bool isLoadn) {
_isLoading = isLoadn;
notifyListeners();
}
Future<bool> signIn(String email, String password) async {
// Validate
if (!isValidForm(email, password)) {
return false;
}
bool successful = false;
pageIsLoading(true);
await _userRepository.login(email, password).then((response){
pageIsLoading(false);
int statusCode = response.statusCode;
var body = json.decode(response.body);
if (statusCode != 200) {
_setErrorMessage("Sorry an error occured!");
successful = false;
} else {
successful = true;
// Set Token
_localStorageService.setLoginToken(body["access_token"]);
_localStorageService.setLoggedInUser(body["user"]);
}
});
return successful;
}
//? Validations
bool isValidForm(String email, String password) {
// Email
if (email.isEmpty) {
_setErrorMessage("Email field is required");
return false;
} else if (!email.contains('@')) {
_setErrorMessage("Please enter a valid email");
return false;
} else if (password.isEmpty) {
_setErrorMessage("Password field is required");
return false;
} else {
return true;
}
}
void _setErrorMessage(String msg) {
_errorMessage = msg;
notifyListeners();
}
}
import 'package:flutter/material.dart';
class LoginPage extends StatelessWidget {
final model = Provider.of<LoginModel>(context);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Profile'),
),
body: FlatButton(
child:Text('login'),
onPressed: () async{
bool isSuccess = await model.signIn(model.email.text, model.password.text);
}
)
);
}
}
import 'package:flutter/material.dart';
import 'package:dummy/view_models/login_model.dart';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
import 'app.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<LoginModel>.value(value: LoginModel()),
],
child: MaterialApp(
title: 'Dummy app',
initialRoute: HomePage(),
),
);
}
}
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:dummy/services/constants.dart';
import 'package:dummy/utils/api.dart';
class UserRepository {
//login method
Future<http.Response> login(String email, String password) async {
final body = jsonEncode({"email": email, "password": password});
http.Response response = await http.post(Api.loginApi, body: body, headers: Api.httpHeaders);
print(response.body);
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment