flutter problem : how to navigate to homepage from login - flutter

When I clicking on login then every time showing an error occurs in dialog box
but in my debug console my shown login successfully
I do not understand why login is not happening, it is throwing catch error again and again
While my login in deb console is succesfully
And after login should go to homepage.
this is my auth.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:rest_api_login/utils/api.dart';
import 'package:http/http.dart' as http;
import 'package:rest_api_login/utils/http_exception.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Auth with ChangeNotifier {
var MainUrl = Api.authUrl;
var AuthKey = Api.authKey;
// String _token;
String _uid;
String _username;
DateTime _expiryDate;
Timer _authTimer;
bool get isAuth {
return token != null;
}
String get token {
if (_expiryDate != null &&
_expiryDate.isAfter(DateTime.now()) &&
_uid != null) {
return _uid;
}
}
String get uid {
return _uid;
}
String get username {
return _username;
}
Future<void> logout() async {
_username = null;
_uid = null;
_expiryDate = null;
if (_authTimer != null) {
_authTimer.cancel();
_authTimer = null;
}
notifyListeners();
final pref = await SharedPreferences.getInstance();
pref.clear();
}
void _autologout() {
if (_authTimer != null) {
_authTimer.cancel();
}
final timetoExpiry = _expiryDate.difference(DateTime.now()).inSeconds;
_authTimer = Timer(Duration(seconds: timetoExpiry), logout);
}
Future<bool> tryautoLogin() async {
final pref = await SharedPreferences.getInstance();
if (!pref.containsKey('userData')) {
return false;
}
final extractedUserData =
json.decode(pref.getString('userData')) as Map<String, Object>;
final expiryDate = DateTime.parse(extractedUserData['expiryDate']);
if (expiryDate.isBefore(DateTime.now())) {
return false;
}
_uid = extractedUserData['uid'];
_username = extractedUserData['username'];
_expiryDate = expiryDate;
notifyListeners();
_autologout();
return true;
}
Future<void> Authentication(
String username, String password, String endpoint) async {
try {
var url = Uri.parse('$MainUrl&action=$endpoint');
final responce = await http.post(url,
body: ({
'username': username,
'password': password,
}));
final responceData = json.decode(responce.body);
print(responceData);
if (responceData['error'] != null) {
throw HttpException(responceData['error']['msg']);
}
_uid = responceData['uid'];
_username = responceData['username'];
_expiryDate = DateTime.now()
.add(Duration(seconds: int.parse(responceData['expiresIn'])));
_autologout();
notifyListeners();
final prefs = await SharedPreferences.getInstance();
final userData = json.encode({
'uid': _uid,
'username': _username,
'expiryDate': _expiryDate.toIso8601String(),
});
prefs.setString('userData', userData);
print('check' + userData.toString());
} catch (e) {
throw e;
}
}
Future<void> login(String username, String password) {
return Authentication(username, password, 'login');
}
Future<void> signUp(String username, String password) {
return Authentication(username, password, 'registration');
}
}
This is my login.dart page
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:rest_api_login/providers/auth.dart';
import 'package:rest_api_login/screens/home_Screen.dart';
import 'package:rest_api_login/screens/signup_screen.dart';
import 'package:rest_api_login/utils/http_exception.dart';
class LoginScreen extends StatefulWidget {
static const String routeName = "/login";
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final GlobalKey<FormState> _formKey = GlobalKey();
Map<String, String> _authData = {'username': '', 'password': ''};
Future _submit() async {
if (!_formKey.currentState.validate()) {
//invalid
return;
}
_formKey.currentState.save();
try {
await Provider.of<Auth>(context, listen: false)
.login(_authData['username'], _authData['password']);
} on HttpException catch (e) {
var errorMessage = 'Authentication Failed';
if (e.toString().contains('INVALID_EMAIL')) {
errorMessage = 'Invalid email';
_showerrorDialog(errorMessage);
} else if (e.toString().contains('EMAIL_NOT_FOUND')) {
errorMessage = 'This email not found';
_showerrorDialog(errorMessage);
} else if (e.toString().contains('INVALID_PASSWORD')) {
errorMessage = 'Invalid Password';
_showerrorDialog(errorMessage);
}
} catch (error) {
var errorMessage = 'Plaese try again later';
_showerrorDialog(errorMessage);
}
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
// backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Container(
child: Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.65,
width: MediaQuery.of(context).size.width * 0.85,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topRight: Radius.circular(360),
bottomRight: Radius.circular(360)),
color: Colors.blue),
),
Container(
padding:
EdgeInsets.only(top: 50, left: 20, right: 20, bottom: 50),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Sign In",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 40),
),
SizedBox(
height: 10,
),
Text(
"Sign in with your username or email",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 10),
),
Form(
key: _formKey,
child: Container(
padding: EdgeInsets.only(top: 50, left: 20, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Username or Email",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.person,
color: Colors.white,
)),
// validator: (value) {
// if (value.isEmpty || !value.contains('#')) {
// return 'Invalid email';
// }
// },
onSaved: (value) {
_authData['username'] = value;
},
),
SizedBox(
height: 10,
),
Text(
"Password",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
obscureText: true,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.vpn_key,
color: Colors.white,
)),
validator: (value) {
if (value.isEmpty || value.length < 5) {
return 'Password is to Short';
}
},
onSaved: (value) {
_authData['password'] = value;
},
),
Container(
padding: EdgeInsets.only(top: 40),
width: 140,
child: RaisedButton(
onPressed: () {
_submit();
},
shape: RoundedRectangleBorder(
borderRadius:
new BorderRadius.circular(10.0),
),
child: Text(
'Sign In',
style: TextStyle(color: Colors.white),
),
color: Colors.green),
),
Align(
alignment: Alignment.bottomRight,
child: InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (ctx) => SignUpScreen()));
},
child: Container(
padding: EdgeInsets.only(top: 90),
child: Text(
"Create Account",
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.blue,
fontSize: 16),
),
),
),
)
],
),
),
),
],
),
),
],
),
),
),
);
}
void _showerrorDialog(String message) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(
'An Error Occurs',
style: TextStyle(color: Colors.blue),
),
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
);
}
}
This is my main.dart page
import 'package:flutter/material.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Providers/signup_auth.dart';
import 'package:login_and_signup/Screens/home_screen.dart';
import 'package:login_and_signup/Screens/login.dart';
import 'package:login_and_signup/Screens/splash_screen.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider.value(
value: Auth(),
child: Consumer<Auth>(
builder: (context, auth, _) => MaterialApp(
title: 'Flutter demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity),
//home: LoginScreen(),
home: auth.isAuth!
? HomeScreen()
: FutureBuilder(
future: auth.tryautoLogin(),
builder: (context, snapshot) =>
snapshot.connectionState == ConnectionState.waiting
? SplashScreen()
: LoginScreen()),
),
),
);
}
}
This is my homepage.dart page
import 'package:flutter/material.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Screens/login.dart';
// import 'package:login_signup_with_api/Providers/auth.dart';
import 'package:provider/provider.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home"),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.of(context).pushReplacementNamed('/');
Provider.of<Auth>(context, listen: false).logout();
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
child: Text('logout'),
color: Colors.green,
)
// color: Colors.green,
// ),
),
);
}
}

Related

Error: NoSuchMethodError: 'then' Dynamic call of null. Receiver: null

Does anyone know the cause of this error? I have tried many ways but still don't know where the problem is.
Database.dart
import 'package:fitness_app/Login/login_data.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseService {
static final DatabaseService _databaseService = DatabaseService._internal();
factory DatabaseService() => _databaseService;
DatabaseService._internal();
static Database? _database;
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
final databasePath = await getDatabasesPath();
final path = join(databasePath, 'conference.database');
return await openDatabase(
path,
onCreate: _onCreate,
version: 1,
onConfigure: (db) async => await db.execute('PRAGMA foreign_keys = ON'),
);
}
Future<void> _onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE login(id INTEGER PRIMARY KEY, name TEXT, username TEXT, password TEXT)',
);
}
verifyuser(String user, String pass) {}
insertLoginData(Logindata logindata) {}
}
Login.dart
import 'package:fitness_app/Login/signup.dart';
import 'package:flutter/material.dart';
import 'login_data.dart';
import 'package:fitness_app/Database/database.dart';
import 'package:fitness_app/home_page.dart';
class Login extends StatefulWidget {
const Login({Key? key, this.login}) : super(key: key);
final Logindata? login;
#override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
String email = "a";
String pass = "a";
TextEditingController emails = TextEditingController();
TextEditingController password = TextEditingController();
final _formKey = GlobalKey<FormState>();
static final List<Logindata> _login = [];
final DatabaseService _databaseService = DatabaseService();
Future<List<Logindata>> _getLogin() async {
await _databaseService.verifyuser(email, pass).then((value) {
if (value) {
AlertDialog alert = AlertDialog(
title: const Text('Login successful!'),
content: const Text('Welcome!'),
actions: <Widget>[
TextButton(
onPressed: () => (Navigator.push(
context,
MaterialPageRoute(builder: (context) => const HomePage()),
)),
child: const Text('OK'),
),
],
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
} else {
AlertDialog alert = AlertDialog(
title: const Text('Error!'),
content: const Text('Wrong Email or Password'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'OK'),
child: const Text('OK'),
),
],
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
});
return _login;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SingleChildScrollView(
child: Column(
children: [
Container(
padding: EdgeInsets.all(10),
child: Form(
key: _formKey,
child: Column(
children: [
Text(
'BeFit:Fitness Activity Tracker Progress\n\n',
style: TextStyle(fontSize: 24),
textAlign: TextAlign.start,
),
Text(
'Welcome',
style: TextStyle(fontSize: 40),
textAlign: TextAlign.center,
),
SizedBox(
height: 30,
),
Container(
child: TextFormField(
controller: emails,
decoration: InputDecoration(
border: UnderlineInputBorder(
borderSide:
BorderSide(width: 1, color: Colors.grey)),
labelText: 'Email'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Email is required';
}
return null;
},
),
),
SizedBox(
height: 20,
),
Container(
child: TextFormField(
controller: password,
obscureText: true,
decoration: InputDecoration(
border: UnderlineInputBorder(
borderSide:
BorderSide(width: 1, color: Colors.grey)),
labelText: 'Password'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Password is required';
}
return null;
},
),
),
SizedBox(
height: 20,
),
Container(
width: MediaQuery.of(context).size.width,
height: 50,
child: FlatButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
email = emails.text;
pass = password.text;
_getLogin();
print(email);
print(pass);
print('success');
}
},
child: Text("Login"),
textColor: Colors.white,
color: Colors.deepPurple[400],
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10)),
),
),
SizedBox(
height: 20,
),
Container(
child: Row(
children: <Widget>[
Text('Does not have account?'),
FlatButton(
textColor: Colors.deepPurpleAccent[100],
child: Text(
'Sign up',
style: TextStyle(fontSize: 16),
),
onPressed: () {
//signup screen
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SignUp()),
);
},
)
],
mainAxisAlignment: MainAxisAlignment.center,
))
],
),
),
)
],
),
),
),
);
}
}
Here is the error
enter image description here
I'm using this flutter to complete my project but there are some errors that I can't solve it. Sorry if my coding looks not right because still lacks in coding
Your verifyuser function does not return anything so your value returns null. You either need to return something or check for null values in your then statement.
Future<String> verifyuser(String user, String pass)async {
return user + pass;
}

Null value comes from singleton structure

I am developing an application with flutter. I set up a singleton structure to access the data in shared preferences. I made a password change area in the settings section of the application. And I wrote the service with node js, everything works fine, but the email value is null.
how can i fix the problem
data_store (singleton)
class DataStore {
static DataStore? _dataStore;
static DataStore? getInstance() {
if (_dataStore == null) {
// keep local instance till it is fully initialized.
var data = DataStore._();
_dataStore = data;
}
return _dataStore;
}
DataStore._();
UserModel user = UserModel();
bool? putUser(UserModel user) {
this.user = user;
return null;
}
UserModel? getUser() {
return user;
}
}
change password page
import 'package:flutter/material.dart';
import 'package:meetdy/Constants/Utils/app_shared_preferences.dart';
import 'package:meetdy/Constants/colors.dart';
import 'package:meetdy/Constants/utils/data_store.dart';
import 'package:meetdy/Models/auth_models/change_passsword_models/change_password_req_model.dart';
import 'package:meetdy/Models/auth_models/user_model.dart';
import 'package:meetdy/Services/auth_services/change_password_services/change_password_services.dart';
import 'package:provider/provider.dart';
import 'package:sizer/sizer.dart';
class ChangePasswordScreen extends StatefulWidget {
const ChangePasswordScreen({Key? key}) : super(key: key);
#override
State<ChangePasswordScreen> createState() => _ChangePasswordScreenState();
}
class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
late Size size = MediaQuery.of(context).size;
bool _isObscure = true;
bool isLoading = false;
final _formKey = GlobalKey<FormState>();
final _passwordController = TextEditingController();
final DataStore? _dataStore = DataStore.getInstance();
UserModel? user;
#override
void initState() {
user = _dataStore?.getUser();
super.initState();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: GestureDetector(
onTap: () {
FocusManager.instance.primaryFocus?.unfocus();
},
child: Scaffold(
appBar: buildAppBar(context),
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 3.h, vertical: 1.h),
child: Column(
children: [
SizedBox(height: 2.h),
// Login TextFields
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Form(
key: _formKey,
child: TextFormField(
obscureText: _isObscure,
controller: _passwordController,
cursorColor: AppColors.lightBlack,
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(
_isObscure
? Icons.visibility
: Icons.visibility_off,
color: Colors.grey,
),
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
}),
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
disabledBorder: InputBorder.none,
labelText: 'Password',
labelStyle: TextStyle(
color: AppColors.lightBlack,
),
),
validator: (value) {
if (value!.isEmpty) {
return 'Required';
} else if (value.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
},
onSaved: (value) {
_passwordController.text = value!;
},
),
),
SizedBox(height: 4.h),
Consumer<ChangePasswordService>(
builder: (context, provider, child) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
"Update",
style: TextStyle(
fontSize: 22.sp,
color: AppColors.black,
fontWeight: FontWeight.w300),
),
Padding(
padding:
EdgeInsets.symmetric(horizontal: 1.0.h)),
isLoading
? CircularProgressIndicator(
color: AppColors.orange)
: FloatingActionButton(
backgroundColor: AppColors.orange,
onPressed: () async {
final form = _formKey.currentState;
if (!form!.validate()) {
return;
}
setState(() {
isLoading = true;
});
String password =
_passwordController.text.trim();
String? email = user!.email;
ChangePasswordReqModel passwordData =
ChangePasswordReqModel(
email: email,
password: password);
var newPassword = await provider
.changePassword(passwordData);
setState(() {
isLoading = false;
});
if (newPassword?.error != null) {
var snackBar = SnackBar(
content: Text(
newPassword?.error?.message ??
""),
duration: Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20)),
clipBehavior: Clip.hardEdge,
);
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context)
.showSnackBar(snackBar);
} else {
var snackBar = SnackBar(
content: Text(
"Your password has been successfully changed"),
duration: Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20)),
clipBehavior: Clip.hardEdge,
);
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context)
.showSnackBar(snackBar);
}
_passwordController.clear();
},
child: Icon(
Icons.keyboard_arrow_right_sharp))
]);
})
],
),
),
],
),
),
),
),
);
}
AppBar buildAppBar(BuildContext context) {
return AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
title: Text(
"Change Password",
style: TextStyle(
color: AppColors.lightBlack,
),
),
leading: IconButton(
icon: Icon(Icons.arrow_back, color: AppColors.lightBlack),
onPressed: () => Navigator.of(context).pop(),
),
);
}
}

There is a token error when logging in to the flutter app

I have a problem when I want to login in my flutter application. when you have entered your email and password then click the login button, it only processes loading but cannot go to the home page. and in android studio an error appears like the image I sent.
this is a picture of the running error
api_service.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../model/login_model.dart';
class APIService {
Future<LoginResponseModel> login(LoginRequestModel requestModel) async {
String url = "http://192.168.100.211:8080/login";
final response = await http.post(url, body: requestModel.toJson());
if (response.statusCode == 200 || response.statusCode == 400) {
return LoginResponseModel.fromJson(
json.decode(response.body),
);
} else {
throw Exception('Failed to load data!');
}
}
}
login_model.dart
class LoginResponseModel {
final String token;
final String error;
LoginResponseModel({this.token, this.error});
factory LoginResponseModel.fromJson(Map<String, dynamic> json) {
return LoginResponseModel(
token: json["token"] != null ? json["token"] : "",
error: json["error"] != null ? json["error"] : "",
);
}
}
class LoginRequestModel {
String email;
String password;
LoginRequestModel({
this.email,
this.password,
});
Map<String, dynamic> toJson() {
Map<String, dynamic> map = {
'email': email.trim(),
'password': password.trim(),
};
return map;
}
}
login_page.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_crud_api_sample_app/beranda/beranda_view.dart';
import '/api/api_service.dart';
import '/model/login_model.dart';
import '../ProgressHUD.dart';
class LoginPage extends StatefulWidget {
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
bool hidePassword = true;
bool isApiCallProcess = false;
GlobalKey<FormState> globalFormKey = GlobalKey<FormState>();
LoginRequestModel loginRequestModel;
final scaffoldKey = GlobalKey<ScaffoldState>();
#override
void initState() {
super.initState();
loginRequestModel = new LoginRequestModel();
}
#override
Widget build(BuildContext context) {
return ProgressHUD(
child: _uiSetup(context),
inAsyncCall: isApiCallProcess,
opacity: 0.3,
);
}
Widget _uiSetup(BuildContext context) {
return Scaffold(
key: scaffoldKey,
backgroundColor: Theme.of(context).accentColor,
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
Container(
width: double.infinity,
padding: EdgeInsets.symmetric(vertical: 30, horizontal: 20),
margin: EdgeInsets.symmetric(vertical: 85, horizontal: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Theme.of(context).primaryColor,
boxShadow: [
BoxShadow(
color: Theme.of(context).hintColor.withOpacity(0.2),
offset: Offset(0, 10),
blurRadius: 20)
],
),
child: Form(
key: globalFormKey,
child: Column(
children: <Widget>[
SizedBox(height: 25),
Text(
"Login",
style: Theme.of(context).textTheme.headline2,
),
SizedBox(height: 20),
new TextFormField(
keyboardType: TextInputType.emailAddress,
onSaved: (input) => loginRequestModel.email = input,
validator: (input) => !input.contains('#')
? "Email Id should be valid"
: null,
decoration: new InputDecoration(
hintText: "Email Address",
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context)
.accentColor
.withOpacity(0.2))),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).accentColor)),
prefixIcon: Icon(
Icons.email,
color: Theme.of(context).accentColor,
),
),
),
SizedBox(height: 20),
new TextFormField(
style:
TextStyle(color: Theme.of(context).accentColor),
keyboardType: TextInputType.text,
onSaved: (input) =>
loginRequestModel.password = input,
validator: (input) => input.length < 3
? "Password should be more than 3 characters"
: null,
obscureText: hidePassword,
decoration: new InputDecoration(
hintText: "Password",
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context)
.accentColor
.withOpacity(0.2))),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).accentColor)),
prefixIcon: Icon(
Icons.lock,
color: Theme.of(context).accentColor,
),
suffixIcon: IconButton(
onPressed: () {
setState(() {
hidePassword = !hidePassword;
});
},
color: Theme.of(context)
.accentColor
.withOpacity(0.4),
icon: Icon(hidePassword
? Icons.visibility_off
: Icons.visibility),
),
),
),
SizedBox(height: 30),
FlatButton(
padding: EdgeInsets.symmetric(
vertical: 12, horizontal: 80),
onPressed: () {
if (validateAndSave()) {
print(loginRequestModel.toJson());
setState(() {
isApiCallProcess = true;
});
APIService apiService = new APIService();
apiService.login(loginRequestModel).then((value) {
if (value != null) {
setState(() {
isApiCallProcess = false;
});
if (value.token.isNotEmpty) {
final snackBar = SnackBar(
content: Text("Login Successful"));
scaffoldKey.currentState
.showSnackBar(snackBar);
} else {
final snackBar =
SnackBar(content: Text(value.error));
scaffoldKey.currentState
.showSnackBar(snackBar);
}
}
});
}
},
child: Text(
"Login",
style: TextStyle(color: Colors.white),
),
color: Theme.of(context).accentColor,
shape: StadiumBorder(),
),
SizedBox(height: 15),
],
),
),
),
],
),
],
),
),
);
}
bool validateAndSave() {
final form = globalFormKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
}
can friends help me to overcome these obstacles?
I suggest you to use print and see your data result from api-call..
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../model/login_model.dart';
class APIService {
Future<LoginResponseModel> login(LoginRequestModel requestModel) async {
String url = "http://192.168.100.211:8080/login";
final response = await http.post(url, body: requestModel.toJson());
print (response)
if (response.statusCode == 200 || response.statusCode == 400) {
return LoginResponseModel.fromJson(
json.decode(response.body),
);
} else {
throw Exception('Failed to load data!');
}
}
}

List is not updating - Flutter

I've saw a code snippet for my app that i wanted to usw.. my problem now is that when i'm typing a new task into the app, my app just won't show that to the screen until a hot reload of the app. But first the user can't do any hot reloads AND for user experience it's very bad. If you need more code or debug things, please ask in the comments!
Here i the code (Ig it's this part thats not updating):
tasks_data.dart
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:learnon/models/task.dart';
import 'dart:collection';
import 'package:shared_preferences/shared_preferences.dart';
int id = 0;
List<Task> _taskList = [];
class TaskData extends ChangeNotifier {
List<String>? task = [];
List<String>? boxValue = [];
List<String>? dates = [];
List<String>? uid = [];
Future getData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//prefs.clear();
task!.clear();
boxValue!.clear();
_taskList.clear();
task = prefs.getStringList("task");
boxValue = prefs.getStringList("check");
dates = prefs.getStringList("date");
uid = prefs.getStringList("id");
if (task == null) {
task = ["Long Press to clear tasks"];
boxValue = ["false"];
dates = ["2021-05-24 02:18:04Z"];
uid = [id.toString()];
}
for (int i = 0; i < boxValue!.length; i++) {
_taskList.add(Task(
name: task![i],
isDone: boxValue![i] == 'true',
date: DateTime.parse(dates![i]),
id: int.parse(uid![i])));
}
id = int.parse(uid!.last);
id += 2;
notifyListeners();
}
void setData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
task!.clear();
boxValue!.clear();
dates!.clear();
uid!.clear();
for (int i = 0; i < _taskList.length; i++) {
task!.add(_taskList[i].name!);
boxValue!.add(_taskList[i].isDone.toString());
dates!.add(_taskList[i].date.toString());
uid!.add(_taskList[i].id.toString());
}
await prefs.setStringList("task", task!);
await prefs.setStringList("check", boxValue!);
await prefs.setStringList("date", dates!);
await prefs.setStringList("id", uid!);
notifyListeners();
}
UnmodifiableListView<Task> get tasks {
return UnmodifiableListView(_taskList);
}
void addTask(String t, DateTime d, int uid) {
_taskList.add(Task(name: t, date: d, id: uid));
setData();
notifyListeners();
}
int get taskCount {
return _taskList.length;
}
void updateTask(Task task) {
task.toggleDone();
setData();
notifyListeners();
}
void deleteTask(Task t) {
_taskList.remove(t);
setData();
notifyListeners();
}
}
tasksscreen.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:learnon/widgets/tasks_list.dart';
import 'package:learnon/screens/add_task_screen.dart';
import 'package:learnon/models/tasks_data.dart';
import 'package:provider/provider.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import '../widgets/app_drawer.dart';
bool theme = false;
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
class TasksScreenNew extends StatelessWidget {
static const routeName = "/tasksnew";
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<TaskData>(
create: (_) => TaskData(),
builder: (context, __) => Scaffold(
appBar: AppBar(
title: Text("Tasks"),
centerTitle: true,
),
drawer: AppDrawer(),
backgroundColor: Colors.blueAccent,
floatingActionButton: FloatingActionButton(
heroTag: null,
child: Icon(Icons.add),
backgroundColor: Colors.lightBlue,
onPressed: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (BuildContext context) => AddTaskScreen());
},
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: EdgeInsets.only(
top: 60, left: 30, right: 30, bottom: 30),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Builder(
builder: (context) => FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.black,
child: Icon(
Icons.refresh,
color: Colors.blueAccent,
size: 30,
),
),
),
SizedBox(
height: 10,
),
Text(
'Tasks',
style: TextStyle(
color: Colors.white,
fontSize: 50,
fontWeight: FontWeight.bold),
),
Text(
'${Provider.of<TaskData>(context).taskCount} Task(s) übrig',
style: TextStyle(fontSize: 18, color: Colors.white),
),
],
),
),
Expanded(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: TasksList(),
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
color: Colors.black),
),
)
]),
));
}
}
// CircleAvatar(
// radius: 30,
// backgroundColor: Colors.white,
// child: Icon(
// Icons.list,
// color: Colors.blueAccent,
// size: 30,
// ),
// )
tasks_list.dart
import 'package:flutter/material.dart';
import 'package:learnon/screens/tasksscreennew.dart';
import 'package:learnon/widgets/task_tile.dart';
import 'package:provider/provider.dart';
import 'package:learnon/models/tasks_data.dart';
import 'dart:core';
class TasksList extends StatefulWidget {
#override
State<TasksList> createState() => _TasksListState();
}
class _TasksListState extends State<TasksList> {
#override
Widget build(BuildContext context) {
return Consumer<TaskData>(
builder: (context, taskData, child) {
return ListView.builder(
itemBuilder: (context, index) {
return TaskTile(
taskTitle: taskData.tasks[index].name,
isChecked: taskData.tasks[index].isDone,
timeLeft: taskData.tasks[index].date!
.difference(DateTime.now())
.inMinutes >
0
? ('${taskData.tasks[index].date!.difference(DateTime.now()).inHours.toString()} Hours left')
: 'Time Expired',
checkboxCallback: (checkBoxState) {
taskData.updateTask(taskData.tasks[index]);
},
longPressCallback: () {
if ((taskData.tasks[index].id!) != 0 ||
(taskData.tasks[index].id!) != 1) {
flutterLocalNotificationsPlugin
.cancel(taskData.tasks[index].id!);
flutterLocalNotificationsPlugin
.cancel(taskData.tasks[index].id! + 1);
}
taskData.deleteTask(taskData.tasks[index]);
},
notificationCallback: () {
flutterLocalNotificationsPlugin
.cancel(taskData.tasks[index].id!);
flutterLocalNotificationsPlugin
.cancel(taskData.tasks[index].id! + 1);
},
);
},
itemCount: taskData.taskCount,
);
},
);
}
}
task_tile.dart
import 'package:flutter/material.dart';
class TaskTile extends StatelessWidget {
final bool? isChecked;
final String? taskTitle;
final Function? checkboxCallback;
final Function longPressCallback;
final Function notificationCallback;
final String? timeLeft;
TaskTile(
{this.isChecked = false,
this.taskTitle,
this.checkboxCallback,
required this.longPressCallback,
this.timeLeft,
required this.notificationCallback()});
#override
Widget build(BuildContext context) {
return ListTile(
onLongPress: () {
longPressCallback();
},
title: Text(
taskTitle!,
style: TextStyle(
fontSize: 20,
color: (timeLeft!) == 'Time Expired'
? Colors.red
: isChecked!
? Colors.green
: null,
),
),
subtitle: Text(
isChecked! ? 'Completed' : (timeLeft!),
style: TextStyle(
color: (timeLeft!) == 'Time Expired'
? Colors.red
: isChecked!
? Colors.green
: null,
),
),
trailing: Checkbox(
activeColor: Colors.lightBlueAccent,
value: isChecked,
onChanged: (value) {
if (value == true) {
notificationCallback();
}
checkboxCallback!(value);
},
),
);
}
}
addtaskscreen.dart
// ignore_for_file: deprecated_member_use
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:learnon/models/tasks_data.dart';
import 'package:date_field/date_field.dart';
import 'package:learnon/screens/tasksscreennew.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
String? newTaskTitle;
DateTime? dateTime;
class AddTaskScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<TaskData>(
create: (_) => TaskData(),
builder: (context, __) => Container(
height: MediaQuery.of(context).viewInsets.bottom + 300,
color: Colors.black,
child: Container(
height: MediaQuery.of(context).viewInsets.bottom + 300,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 50, vertical: 30),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'Task hinzufügen',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 25),
),
TextField(
// controller: myController,
autofocus: true,
textAlign: TextAlign.center,
onChanged: (value) {
newTaskTitle = value;
},
),
SizedBox(
height: 10,
),
Text(
'Abgabedatum',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 25),
),
SizedBox(
height: 10,
),
DateTimeFormField(
decoration: const InputDecoration(
hintStyle: TextStyle(color: null),
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.event_note),
),
mode: DateTimeFieldPickerMode.dateAndTime,
initialDatePickerMode: DatePickerMode.day,
firstDate: DateTime.now(),
autovalidateMode: AutovalidateMode.always,
validator: (e) => (e?.day ?? 0) == 1
? 'Please not the first day'
: null,
onDateSelected: (DateTime value) {
dateTime = value;
},
),
TextButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.green),
),
autofocus: false,
onPressed: () async {
print(newTaskTitle);
print(dateTime);
Provider.of<TaskData>(context, listen: false)
.addTask(newTaskTitle!, dateTime!, id);
await flutterLocalNotificationsPlugin.schedule(
id++,
'Zeit abgelaufen',
newTaskTitle!,
dateTime!,
const NotificationDetails(
android: AndroidNotificationDetails(
'1', 'Zeit abgelaufen')),
androidAllowWhileIdle: true,
);
await flutterLocalNotificationsPlugin.schedule(
id++,
dateTime!.difference(DateTime.now()).inMinutes /
2 <
60
? '${dateTime!.difference(DateTime.now()).inMinutes / 2} Minuten übrig'
: '${dateTime!.difference(DateTime.now()).inHours / 2} Stunden übrig',
newTaskTitle!,
dateTime!.subtract(Duration(
minutes: dateTime!
.difference(DateTime.now())
.inMinutes ~/
2)),
const NotificationDetails(
android: AndroidNotificationDetails(
'5', 'Reminder')),
androidAllowWhileIdle: true,
);
Navigator.pop(context);
},
child: Text(
'Hinzufügen',
style: TextStyle(
color: Colors.white,
// backgroundColor: Colors.lightBlueAccent,
fontSize: 20,
),
),
)
],
),
),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
)),
));
}
}
Since you're making your TaskData as a **ChangeNotifier, are you wrapping your widget inside a Consumer widget, and using this class inside the Consumer widget, like this:
Consumer<TaskData>(
builder: (context, taskData, child) {
return <YOUR_WIDGET_HERE>;
}
)
That way all changes you make via your service class should be reflected and trigger a rebuild on your widget?
Also are you using a MultiProvider widget, how are you providing this class?

The getter 'totalCartPrice' was called on null. Receiver: null Tried calling: totalCartPrice

The app itself works well. The product is added to the cart, but when you go to the cart page, this error appears. Maybe someone came across. I looked at similar errors, but my solution did not help.
The getter 'totalCartPrice' was called on null. Receiver: null Tried calling: totalCartPrice
enter code here
import 'package:flutter/material.dart';
import 'package:food_course/scr/helpers/order.dart';
import 'package:food_course/scr/helpers/style.dart';
import 'package:food_course/scr/models/cart_item.dart';
import 'package:food_course/scr/models/products.dart';
import 'package:food_course/scr/providers/app.dart';
import 'package:food_course/scr/providers/user.dart';
import 'package:food_course/scr/widgets/custom_text.dart';
import 'package:food_course/scr/widgets/loading.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
class CartScreen extends StatefulWidget {
#override
_CartScreenState createState() => _CartScreenState();
}
class _CartScreenState extends State<CartScreen> {
final _key = GlobalKey<ScaffoldState>();
OrderServices _orderServices = OrderServices();
#override
Widget build(BuildContext context) {
final user = Provider.of<UserProvider>(context);
final app = Provider.of<AppProvider>(context);
return Scaffold(
key: _key,
appBar: AppBar(
iconTheme: IconThemeData(color: black),
backgroundColor: white,
elevation: 0.0,
title: CustomText(text: "Shopping Cart"),
leading: IconButton(
icon: Icon(Icons.close),
onPressed: () {
Navigator.pop(context);
}),
),
backgroundColor: white,
body: app.isLoading ? Loading() : ListView.builder(
itemCount: user.userModel.cart.length,
itemBuilder: (_, index) {
return Padding(
padding: const EdgeInsets.all(16),
child: Container(
height: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: white,
boxShadow: [
BoxShadow(
color: red.withOpacity(0.2),
offset: Offset(3, 2),
blurRadius: 30)
]),
child: Row(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
topLeft: Radius.circular(20),
),
child: Image.network(
user.userModel.cart[index].image,
height: 120,
width: 140,
fit: BoxFit.fill,
),
),
SizedBox(
width: 10,
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
RichText(
text: TextSpan(children: [
TextSpan(
text: user.userModel.cart[index].name+ "\n",
style: TextStyle(
color: black,
fontSize: 20,
fontWeight: FontWeight.bold)),
TextSpan(
text: "\$${user.userModel.cart[index].price / 100} \n\n",
style: TextStyle(
color: black,
fontSize: 18,
fontWeight: FontWeight.w300)),
TextSpan(
text: "Quantity: ",
style: TextStyle(
color: grey,
fontSize: 16,
fontWeight: FontWeight.w400)),
TextSpan(
text: user.userModel.cart[index].quantity.toString(),
style: TextStyle(
color: primary,
fontSize: 16,
fontWeight: FontWeight.w400)),
]),
),
IconButton(
icon: Icon(
Icons.delete,
color: red,
),
onPressed: ()async{
app.changeLoading();
bool value = await user.removeFromCart(cartItem: user.userModel.cart[index]);
if(value){
user.reloadUserModel();
print("Item added to cart");
_key.currentState.showSnackBar(
SnackBar(content: Text("Removed from Cart!"))
);
app.changeLoading();
return;
}else{
print("ITEM WAS NOT REMOVED");
app.changeLoading();
}
})
],
),
)
],
),
),
);
}),
bottomNavigationBar: Container(
height: 70,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
RichText(
text: TextSpan(children: [
TextSpan(
text: "Total: ",
style: TextStyle(
color: grey,
fontSize: 22,
fontWeight: FontWeight.w400)),
TextSpan(
text: " \$${user.userModel.totalCartPrice / 100}",
style: TextStyle(
color: primary,
fontSize: 22,
fontWeight: FontWeight.normal)),
]),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20), color: primary),
child: FlatButton(
onPressed: () {
if(user.userModel.totalCartPrice == 0){
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20.0)), //this right here
child: Container(
height: 200,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Your cart is emty', textAlign: TextAlign.center,),
],
),
],
),
),
),
);
});
return;
}
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20.0)), //this right here
child: Container(
height: 200,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('You will be charged \$${user.userModel.totalCartPrice / 100} upon delivery!', textAlign: TextAlign.center,),
SizedBox(
width: 320.0,
child: RaisedButton(
onPressed: () async{
var uuid = Uuid();
String id = uuid.v4();
_orderServices.createOrder(
userId: user.user.uid,
id: id,
description: "Some random description",
status: "complete",
totalPrice: user.userModel.totalCartPrice,
cart: user.userModel.cart
);
for(CartItemModel cartItem in user.userModel.cart){
bool value = await user.removeFromCart(cartItem: cartItem);
if(value){
user.reloadUserModel();
print("Item added to cart");
_key.currentState.showSnackBar(
SnackBar(content: Text("Removed from Cart!"))
);
}else{
print("ITEM WAS NOT REMOVED");
}
}
_key.currentState.showSnackBar(
SnackBar(content: Text("Order created!"))
);
Navigator.pop(context);
},
child: Text(
"Accept",
style: TextStyle(color: Colors.white),
),
color: const Color(0xFF1BC0C5),
),
),
SizedBox(
width: 320.0,
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
"Reject",
style: TextStyle(color: Colors.white),
),
color: red
),
)
],
),
),
),
);
});
},
child: CustomText(
text: "Check out",
size: 20,
color: white,
weight: FontWeight.normal,
)),
)
],
),
),
),
);
}
}
USER.dart
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:food_course/scr/helpers/order.dart';
import 'package:food_course/scr/helpers/user.dart';
import 'package:food_course/scr/models/cart_item.dart';
import 'package:food_course/scr/models/order.dart';
import 'package:food_course/scr/models/products.dart';
import 'package:food_course/scr/models/user.dart';
import 'package:uuid/uuid.dart';
enum Status{Uninitialized, Authenticated, Authenticating, Unauthenticated}
class UserProvider with ChangeNotifier{
FirebaseAuth _auth;
FirebaseUser _user;
Status _status = Status.Uninitialized;
Firestore _firestore = Firestore.instance;
UserServices _userServicse = UserServices();
OrderServices _orderServices = OrderServices();
UserModel _userModel;
// getter
UserModel get userModel => _userModel;
Status get status => _status;
FirebaseUser get user => _user;
// public variables
List<OrderModel> orders = [];
final formkey = GlobalKey<FormState>();
TextEditingController email = TextEditingController();
TextEditingController password = TextEditingController();
TextEditingController name = TextEditingController();
UserProvider.initialize(): _auth = FirebaseAuth.instance{
_auth.onAuthStateChanged.listen(_onStateChanged);
}
Future<bool> signIn()async{
try{
_status = Status.Authenticating;
notifyListeners();
await _auth.signInWithEmailAndPassword(email: email.text.trim(), password: password.text.trim());
return true;
}catch(e){
_status = Status.Unauthenticated;
notifyListeners();
print(e.toString());
return false;
}
}
Future<bool> signUp()async{
try{
_status = Status.Authenticating;
notifyListeners();
await _auth.createUserWithEmailAndPassword(email: email.text.trim(), password: password.text.trim()).then((result){
_firestore.collection('users').document(result.user.uid).setData({
'name':name.text,
'email':email.text,
'uid':result.user.uid,
"likedFood": [],
"likedRestaurants": []
});
});
return true;
}catch(e){
_status = Status.Unauthenticated;
notifyListeners();
print(e.toString());
return false;
}
}
Future signOut()async{
_auth.signOut();
_status = Status.Unauthenticated;
notifyListeners();
return Future.delayed(Duration.zero);
}
void clearController(){
name.text = "";
password.text = "";
email.text = "";
}
Future<void> reloadUserModel()async{
_userModel = await _userServicse.getUserById(user.uid);
notifyListeners();
}
Future<void> _onStateChanged(FirebaseUser firebaseUser) async{
if(firebaseUser == null){
_status = Status.Unauthenticated;
}else{
_user = firebaseUser;
_status = Status.Authenticated;
_userModel = await _userServicse.getUserById(user.uid);
}
notifyListeners();
}
Future<bool> addToCard({ProductModel product, int quantity})async{
print("THE PRODUC IS: ${product.toString()}");
print("THE qty IS: ${quantity.toString()}");
try{
var uuid = Uuid();
String cartItemId = uuid.v4();
List cart = _userModel.cart;
// bool itemExists = false;
Map cartItem ={
"id": cartItemId,
"name": product.name,
"image": product.image,
"restaurantId": product.restaurantId,
"totalRestaurantSale": product.price * quantity,
"productId": product.id,
"price": product.price,
"quantity": quantity
};
CartItemModel item = CartItemModel.fromMap(cartItem);
// if(!itemExists){
print("CART ITEMS ARE: ${cart.toString()}");
_userServicse.addToCart(userId: _user.uid, cartItem: item);
// }
return true;
}catch(e){
print("THE ERROR ${e.toString()}");
return false;
}
}
getOrders()async{
orders = await _orderServices.getUserOrders(userId: _user.uid);
notifyListeners();
}
Future<bool> removeFromCart({CartItemModel cartItem})async{
print("THE PRODUC IS: ${cartItem.toString()}");
try{
_userServicse.removeFromCart(userId: _user.uid, cartItem: cartItem);
return true;
}catch(e){
print("THE ERROR ${e.toString()}");
return false;
}
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:food_course/scr/providers/app.dart';
import 'package:food_course/scr/providers/category.dart';
import 'package:food_course/scr/providers/product.dart';
import 'package:food_course/scr/providers/restaurant.dart';
import 'package:food_course/scr/providers/user.dart';
import 'package:food_course/scr/screens/home.dart';
import 'package:food_course/scr/screens/login.dart';
import 'package:food_course/scr/screens/splash.dart';
import 'package:food_course/scr/widgets/loading.dart';
import 'package:provider/provider.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MultiProvider(
providers: [
ChangeNotifierProvider.value(value: AppProvider()),
ChangeNotifierProvider.value(value: UserProvider.initialize()),
ChangeNotifierProvider.value(value: CategoryProvider.initialize()),
ChangeNotifierProvider.value(value: RestaurantProvider.initialize()),
ChangeNotifierProvider.value(value: ProductProvider.initialize()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Food App',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: ScreensController())));
}
class ScreensController extends StatelessWidget {
#override
Widget build(BuildContext context) {
final auth = Provider.of<UserProvider>(context);
switch (auth.status) {
case Status.Uninitialized:
return Splash();
case Status.Unauthenticated:
case Status.Authenticating:
return LoginScreen();
case Status.Authenticated:
return Home();
default:
return LoginScreen();
}
}
}