StartDate and EndDate is resetting back Flutter - flutter

Im trying to make changes in the existing code where in Firstpage it take the name of the trip and StartDate and Endate and other details. When the user click on upload image and comeback to main page I'm able to save the other field data in void savedata() but I'm stuck with how to store the data of startdate and enddate what the user has chosen before he going to second page. enter image description here - I have attached the screenshot how it looks when he choose the date and after coming back to firstpage from secondpage it shows like second picture. enter image description here my requirement here is how other field are storing the date I want startdate and enddate also store.
class _MyHomePageState extends State<DataInfoPage> {
_DataInfoPageState createState() => _DataInfoPageState();
String date = "";
final FirebaseAuth _auth = FirebaseAuth.instance;
User? user;
var name = '';
#override
void initState() {
super.initState();
initUser();
savedata();
}
initUser() async {
user = (_auth.currentUser!);
name = user!.displayName!;
setState(() {});
}
void savedata() {
final absavedata = context.read<AddTripBloc>();
if (absavedata.tripname != null) {
tripname.text = absavedata.tripname!;
//_selectedDateRange!.start = absavedata.sdate;
//_selectedDateRange!.end;
noofdays.text = absavedata.noofdays!;
noofnights.text = absavedata.noofnights!;
slotavail.text = absavedata.slotavail!;
priceperpers.text = absavedata.priceperpers!;
}
}
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
// DateTime selectedDate = DateTime.now();
//DateTime startDate = DateTime();
TextEditingController tripname = new TextEditingController();
TextEditingController noofdays = new TextEditingController();
TextEditingController noofnights = new TextEditingController();
TextEditingController slotavail = new TextEditingController();
TextEditingController priceperpers = new TextEditingController();
DateTimeRange? startdate;
DateTimeRange? enddate;
DateTimeRange? _selectedDateRange;
String _displayText(String begin, DateTime? date) {
if (date != null) {
return '$begin Date: ${date.toString().split(' ')[0]}';
} else {
return 'Press the button to show the picker';
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(
height: 20,
),
Text(
"Please enter trip details ",
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
color: Colors.black),
),
SizedBox(
height: 20,
),
Padding(
padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
customfields(
hintValue: ' Enter Trip Name',
labeltxt: 'Trip Name *',
keyboardtype: TextInputType.text,
text: tripname),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
FloatingActionButton(
onPressed: _show,
child: const Icon(Icons.date_range_rounded),
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.circular(5))),
Column(
children: [
Text(
_displayText(
'Start', _selectedDateRange?.start),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Colors.black),
),
SizedBox(
height: 20,
),
Text(
_displayText(
'End', _selectedDateRange?.end),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Colors.black))
],
),
SizedBox(
height: 20,
),
],
),
SizedBox(
height: 20,
),
customfields(
hintValue: ' No.of Days *',
labeltxt: 'No.of Days *',
keyboardtype: TextInputType.number,
text: noofdays),
SizedBox(
height: 20,
),
customfields(
hintValue: 'No.of Nights*',
labeltxt: 'No.of Nights*',
keyboardtype: TextInputType.number,
text: noofnights),
SizedBox(
height: 20,
),
customfields(
hintValue: 'Slots Available: *',
labeltxt: 'Slots Available: *',
keyboardtype: TextInputType.number,
text: slotavail,
),
SizedBox(
height: 20,
),
TextFormField(
style: TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
decoration: InputDecoration(
hintText: 'Price Per Person: *',
labelText: 'Price Per Person: *',
suffixIcon: Icon(
Icons.currency_rupee,
color: Colors.black,
size: 15,
),
),
controller: priceperpers,
keyboardType: TextInputType.number,
validator: (value) {
if (value!.isEmpty) {
return "This Field Can't be empty.";
}
return null;
},
),
// customfields(
// hintValue: 'Price Per Person: *',
// labeltxt: 'Price Per Person: *',
// keyboardtype: TextInputType.number,
// text: priceperpers,
// ),
//Text("Slots Available"),
SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () async {
final ab = context.read<AddTripBloc>();
ab.setpageonedata(
tripname.text,
_selectedDateRange!.start,
_selectedDateRange!.end,
noofdays.text,
noofnights.text,
slotavail.text,
priceperpers.text);
await Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CameraWidget()));
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => CameraWidget()));
},
child: const Text("Upload Images of Trip *"),
),
SizedBox(
height: 35,
),
ElevatedButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
final ab = context.read<AddTripBloc>();
ab.setpageonedata(
tripname.text,
_selectedDateRange!.start,
_selectedDateRange!.end,
noofdays.text,
noofnights.text,
slotavail.text,
priceperpers.text);
//ab.savetripdata(user!);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PageTwo()));
}
setState(() {
_formKey.currentState?.save();
});
},
child: const Text("Save and Continue"),
)
],
)),
],
),
),
));
}
void _show() async {
final DateTimeRange? result = await showDateRangePicker(
context: context,
firstDate: DateTime(2022, 1, 1),
lastDate: DateTime(2030, 12, 31),
currentDate: DateTime.now(),
saveText: 'Done.',
);
if (result != null) {
// Rebuild the UI
String startdate = result.start.toString();
String enddate = result.end.toString();
// print(startdate);
//print(enddate);
//print(result.start.toString());
//print(result.end.toString());
setState(() {
startdate = result.start.toString();
enddate = result.end.toString();
_selectedDateRange = result;
});
}
}
}

Related

Getting error during late initialisation in flutter

I am calling form below for add and edit operations.When clicked on edit button I have to get details of particular document based on its unique Id, so when clicked on edit I am calling API in initState() but when clicked on add button I am facing an issue like futureDocuments is not initialised, I cannot initialise it to null also, how to resolve this?
I am also getting an error like dId is not initialised while cliked on add document button
please guide me towards both the initializations
class DocumentForm extends StatefulWidget {
bool update;
final String userName;
//final String createdBY;
DocumentForm(this.userName, this.update);
#override
State createState() {
return _DocumentFormState(this.userName, this.update);
}
}
// AddAppointmentState<AddDocument> createState() => _AddDocumentState();
class _DocumentFormState extends State<DocumentForm> {
final String userName;
String playerId = '';
bool update;
//final String createdBY;
_DocumentFormState(this.userName, this.update);
late final String date1;
late String datainput;
final List<String> items1 = ["Open", "Closed", "Cancel", "Submitted"];
String? selectedItem;
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
TextEditingController docIdController = TextEditingController();
TextEditingController docTitleController = TextEditingController();
TextEditingController tokenNoController = TextEditingController();
TextEditingController addressController = TextEditingController();
TextEditingController cityController = TextEditingController();
TextEditingController docStatusController = TextEditingController();
TextEditingController docTypeController = TextEditingController();
TextEditingController partyNameController = TextEditingController();
TextEditingController durationController = TextEditingController();
TextEditingController pinCodeController = TextEditingController();
TextEditingController rentDescController = TextEditingController();
TextEditingController startDateController = TextEditingController();
TextEditingController endDateController = TextEditingController();
late TextEditingController docstatusController = TextEditingController();
late String docType = docTypeController.text;
late final String createdBY;
final List<String> items = [
"Residential",
"Commercial",
];
String? selectedValue;
late Future<Document>? futureDocuments;
#override
void initState() {
this.update == true
? futureDocuments = DocumentController.fetchDocumentsByID(this.dId)
: futureDocuments = null;
// TODO: implement initState
super.initState();
// initPlatformState();
// initPlatformStateApt();
init();
}
#override
void dispose() {
docStatusController.dispose();
docTypeController.dispose();
super.dispose();
}
Future init() async {
// initPlatformState();
}
#override
Future<Document>? _futureDocument;
body: SafeArea(
child: SingleChildScrollView(
child: Container(
// height: MediaQuery.of(context).size.height,
//width: width * 1,
//height: MediaQuery.of(context).size.height,
alignment: Alignment.center,
padding: const EdgeInsets.all(25),
child: (_futureDocument == null)
? buildColumn(update)
: buildFutureBuilder(),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10))),
),
),
),
Form buildColumn(bool update) {
return Form(
key: formKey,
child: FutureBuilder<Document>(
future: futureDocuments,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
createdBY = snapshot.data!.createdBy;
this.dId = snapshot.data!.docId;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 5,
),
// SizedBox(
// height: MediaQuery.of(context).size.height * 0.06,
// width: MediaQuery.of(context).size.width * 8,
// child:
Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.95,
height: MediaQuery.of(context).size.height * 0.06,
// height: MediaQuery.of(context).size.height * 0.5,
child: TextFormField(
// minLines: 1,
// maxLines: 5,
// textCapitalization: TextCapitalization.words,
// //autovalidateMode: AutovalidateMode.onUserInteraction,
inputFormatters: [
// LengthLimitingTextInputFormatter(100),
FilteringTextInputFormatter.allow(
RegExp("[ ',-/ a-z A-Z á-ú Á-Ú 0-9]")),
],
controller: this.update == true
? docTitleController = TextEditingController(
text: '${snapshot.data!.docTitle}')
: docTitleController,
style: TextStyle(fontSize: 12),
// keyboardType: TextInputType.multiline,
decoration: const InputDecoration(
errorStyle: const TextStyle(fontSize: 0.05),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(30),
)),
hintStyle: TextStyle(fontSize: 12),
labelStyle: TextStyle(
fontSize: 12,
),
labelText: 'Document Title',
hintText: 'Document title required'),
// validator: ,
validator: MultiValidator(
[RequiredValidator(errorText: 'Required*')]),
),
),
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.06,
width: MediaQuery.of(context).size.width * 0.4,
child: TextFormField(
style: TextStyle(
fontSize: 12,
),
// minLines: 1,
// maxLines: 2,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(14)
],
// //autovalidateMode: AutovalidateMode.onUserInteraction,
controller: this.update == true
? tokenNoController = TextEditingController(
text: '${snapshot.data!.tokenNo}')
: tokenNoController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
errorStyle: const TextStyle(fontSize: 0.05),
counterText: "",
border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(30)),
),
focusColor: Color.fromARGB(255, 3, 87,
156), //Color.fromARGB(255, 253, 153, 33),
hintStyle: TextStyle(fontSize: 12),
labelStyle: TextStyle(
fontSize: 12,
),
labelText: 'Token No',
hintText: 'Token no required'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter token No';
} else if (value.length < 14) {
return 'Please enter 14 digits number';
}
return null;
},
),
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.01,
),
Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.06,
width: MediaQuery.of(context).size.width * 0.4,
child: TextFormField(
style: TextStyle(fontSize: 12),
// minLines: 1,
// maxLines: 2,
//autovalidateMode: AutovalidateMode.onUserInteraction,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(2)
],
controller: this.update == true
? durationController = TextEditingController(
text: '${snapshot.data!.duration}')
: durationController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
errorStyle: const TextStyle(fontSize: 0.05),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(30))),
hintStyle: TextStyle(fontSize: 12),
labelStyle: TextStyle(
fontSize: 12,
),
labelText: 'Duration(M)',
hintText: 'Duration required'),
validator: MultiValidator(
[RequiredValidator(errorText: 'Required*')],
),
),
),
),
],
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.06,
width: MediaQuery.of(context).size.width * 0.4,
child: TextFormField(
style: TextStyle(fontSize: 12),
// //autovalidateMode: AutovalidateMode.onUserInteraction,
//FilteringTextInputFormatter.allow(RegExp("[- 0-9]")),
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp("[- 0-9]")),
LengthLimitingTextInputFormatter(10)
],
controller: this.update == true
? startDateController = TextEditingController(
text: '${snapshot.data!.startDate}')
: startDateController,
keyboardType: TextInputType.datetime,
decoration: const InputDecoration(
errorStyle: const TextStyle(fontSize: 0.05),
prefixIcon: Icon(Icons.calendar_month),
border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(30))),
hintStyle: TextStyle(fontSize: 12),
labelStyle: TextStyle(
fontSize: 12,
),
labelText: 'Start Date',
hintText: 'yyyy-MM-dd',
),
onTap: () async {
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(
1991), //DateTime.now() - not to allow to choose before today.
lastDate: DateTime(2101),
// onConfirm:widget.onChanged,
).then((pickedDate) {
if (pickedDate != null) {
// print(
// pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
String formattedDate =
DateFormat('yyyy-MM-dd')
.format(pickedDate);
print(formattedDate);
setState(() {
startDateController.text = formattedDate;
//set output date to TextField value.
});
print(startDateController.text);
} else {
print("Date is not selected");
}
});
final int dur =
int.parse(durationController.text);
var stDate =
DateTime.parse(startDateController.text);
var jiffy = Jiffy(stDate).add(
months: dur,
days: -1,
// days: 1095,
);
DateTime d = jiffy.dateTime;
String s = jiffy.format('yyyy-MM-dd');
setState(() {
endDateController.text = s.toString();
});
},
validator: MultiValidator(
[RequiredValidator(errorText: 'Required*')]),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
height: 30,
width: 150,
child: ElevatedButton(
onPressed: () {
// ******Add new document **********///////
formKey.currentState?.validate();
final isValidForm =
formKey.currentState!.validate();
if (isValidForm && (update == false)) {
final String docTitle =
docTitleController.text;
final int tokenNo =
int.parse(tokenNoController.text)
.toInt();
//final String tokenNo = tokenNoController.text;
final String partyName =
partyNameController.text;
// addStatus(selectedItem!);
final String docType =
selectedValue.toString();
final String docStatus =
selectedItem.toString();
final String address =
addressController.text;
final String city = cityController.text;
final String rentDesc =
rentDescController.text;
final String pinCode =
pinCodeController.text;
final String duration =
durationController.text;
final String startDate =
startDateController.text;
final String endDate =
endDateController.text;
final String createdBy = this.userName;
print('Username :${createdBy}');
final String updatedBy = '';
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) =>
DocumentPage(
this.userName,
)));
setState(() {
_futureDocument = createDocument(
// docId,
docTitle,
tokenNo,
partyName,
docType,
address,
city,
pinCode,
duration,
rentDesc,
docStatus,
startDate,
endDate,
createdBy,
updatedBy,
// createdAt,
);
});
// }
//}
}
///*****************/
//****Edit document ******/
else if (isValidForm && update == true) {
final int docid = snapshot.data!.docId;
final String docTitle =
docTitleController.text;
final int tokenNo =
int.parse(tokenNoController.text)
.toInt();
final String partyName =
partyNameController.text;
final String docType =
docTypeController.text;
final String city = cityController.text;
final String address =
addressController.text;
final String pinCode =
pinCodeController.text;
final String duration =
durationController.text;
final String rentDesc =
rentDescController.text;
final String docStatus =
docstatusController.text;
final String startDate =
startDateController.text;
final String endDate =
endDateController.text;
final String createdBy = this.createdBY;
final String updatedBy = this.userName;
print(
'the user name from doc edit page ${this.userName}');
setState(() {
futureDocuments = updateDocument(
docid,
docTitle,
tokenNo,
partyName,
docType,
address,
city,
pinCode,
duration,
rentDesc,
docStatus,
startDate,
endDate,
createdBy,
updatedBy);
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) =>
DocumentsDetails(
docid,
this.userName,
)));
});
}
;
},
child: const Text("Save"),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Color.fromARGB(255, 253, 153, 33),
//Color.fromARGB(255, 253, 153, 33)
),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(18.0),
//side: BorderSide(color: Colors.red)
),
)))),
],
),
],
);
}
}
return Center(child: const CircularProgressIndicator());
}),
);
//])
//);
}
FutureBuilder<Document> buildFutureBuilder() {
return FutureBuilder<Document>(
future: _futureDocument,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.docTitle);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
);
}
You can remove late since it's already nullable. You have to also update the state after assigning it to futureDocuments.
Change late to nullable values using ? operator. i.e
Change from
late final String date1;
late String datainput;
to
final String? date1;
String? datainput;
Now you can assign null to date1 and datainput!

Add custom validation in Flutter using Firebase

I have made a login page using Flutter which asks for 'Application Number (which are just numbers)', 'Password' & 'DOB' as shown below.
I have already added validations to it like it shouldn't be empty & only numbers & atleast one capital etc. But I also want to add custom validation using Firebase to Application Number & Password where only certain Application Numbers and their corresponding passwords will be allowed to enter which are specified in the database.
I have already added Firebase to my Flutter app.
Here is the code of the login page:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'home.dart';
class WelcomeScreen extends StatefulWidget {
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
DateTime date = DateTime(2005, 06, 13);
TextEditingController dateinput = TextEditingController();
final formKey = GlobalKey<FormState>(); //key for form
String name = "";
#override
void initState() {
dateinput.text = ""; //set the initial value of text field
super.initState();
}
#override
Widget build(BuildContext context) {
final double height = MediaQuery.of(context).size.height;
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
),
backgroundColor: Color(0xFFffffff),
body: Container(
padding: const EdgeInsets.only(left: 40, right: 40),
child: SingleChildScrollView(
child: Form(
key: formKey, //key for form
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: height * 0.04),
Text(
"LEARNERS",
style: TextStyle(fontSize: 30, color: Color(0xFF363f93)),
),
Text(
"LICENSE TEST",
style: TextStyle(fontSize: 30, color: Color(0xFF363f93)),
),
SizedBox(
height: height * 0.05,
),
TextFormField(
decoration:
InputDecoration(labelText: "Enter Application Number"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^[0-9]+$').hasMatch(value)) {
return "This cannot be empty / \nThis can only contain numbers";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.05,
),
TextFormField(
decoration: InputDecoration(labelText: "Enter Password"),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$')
.hasMatch(value)) {
return "Minimum eight characters, \nat least one uppercase letter, \none lowercase letter and one number";
} else {
return null;
}
},
),
SizedBox(
height: height * 0.05,
),
GestureDetector(
child: TextFormField(
style: TextStyle(color: Colors.white),
controller:
dateinput, //editing controller of this TextField
decoration: InputDecoration(
labelStyle: TextStyle(color: Colors.white),
icon: Icon(Icons.calendar_today),
iconColor: Colors.white, //icon of text field
labelText: "Enter Date Of Birth" //label text of field
),
readOnly: true,
validator: (value) {
if (value!.isEmpty) {
return "Please select the Date of Birth";
} else {
return null;
}
}, //set it true, so that user will not able to edit text
onTap: () async {
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: date,
firstDate: DateTime(
1900), //DateTime.now() - not to allow to choose before today.
lastDate: DateTime(2006, 06, 13));
if (pickedDate != null) {
print(
pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
String formattedDate =
DateFormat('dd-MM-yyyy').format(pickedDate);
print(
formattedDate); //formatted date output using intl package => 2021-03-16
//you can implement different kind of Date Format here according to your requirement
setState(() {
dateinput.text =
formattedDate; //set output date to TextField value.
});
} else {
print("Date is not selected");
}
},
),
),
SizedBox(
height: height * 0.08,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CircleAvatar(
radius: 30,
backgroundColor: Color(0xff4c505b),
child: IconButton(
color: Colors.white,
onPressed: () {
if (formKey.currentState!.validate()) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TestScreen()),
);
}
},
icon: Icon(
Icons.arrow_forward,
)),
)
],
)
],
),
),
),
));
}
}

Main page data is resetting automatically Flutter after user come back to second page to first page

I'm stuck with one issue where once I click on the upload image button it will take me to the next page wherein upload image class I will choose the images from the camera or Gallery and I will click on done. In the done button I have written navigation. pop(context) to the first page but when I come back all the text field data is cleared whatever I have entered and again I need to enter it back which is quite frustrating all the time...PLease help me to solve the issue or show the way how to save the data?
import '../blocs/addtrip_bloc.dart';
import '../widgets/customtextformfield.dart';
import 'CameraWidgetState.dart';
class DataInfoPage extends StatefulWidget {
const DataInfoPage({Key? key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<DataInfoPage> {
_DataInfoPageState createState() => _DataInfoPageState();
String date = "";
final FirebaseAuth _auth = FirebaseAuth.instance;
User? user;
var name = '';
#override
void initState() {
super.initState();
initUser();
savedata();
}
initUser() async {
user = (await _auth.currentUser!);
name = user!.displayName!;
setState(() {});
}
void savedata() {
final absavedata = context.read<AddTripBloc>();
}
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
DateTime selectedDate = DateTime.now();
TextEditingController tripname = new TextEditingController();
TextEditingController sdate = new TextEditingController();
DateTimeRange? _selectedDateRange;
String _displayText(String begin, DateTime? date) {
if (date != null) {
return '$begin Date: ${date.toString().split(' ')[0]}';
} else {
return 'Press the button to show the picker';
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(
height: 20,
),
Text(
"Please enter trip details ",
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
color: Colors.black),
),
SizedBox(
height: 20,
),
Padding(
padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
customfields(
hintValue: ' Enter Trip Name',
labeltxt: 'Trip Name *',
keyboardtype: TextInputType.text,
text: tripname),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
FloatingActionButton(
onPressed: _show,
child: const Icon(Icons.date_range),
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.circular(5))),
Column(
children: [
Text(
_displayText(
'Start', _selectedDateRange?.start),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Colors.black),
),
SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () async {
await Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CameraWidget()));
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => CameraWidget()));
},
child: const Text("Upload Images of Trip *"),
),
SizedBox(
height: 35,
),
],
)),
],
),
),
));
}
void _show() async {
final DateTimeRange? result = await showDateRangePicker(
context: context,
firstDate: DateTime(2022, 1, 1),
lastDate: DateTime(2030, 12, 31),
currentDate: DateTime.now(),
saveText: 'Done.',
);
if (result != null) {
// Rebuild the UI
print(result.start.toString());
setState(() {
_selectedDateRange = result;
});
}
}
}
Custom Flied Code
class customfields extends StatelessWidget {
customfields(
{required this.hintValue,
this.labeltxt = "",
required this.keyboardtype,
this.maxvalue = 1,
required this.text});
String hintValue;
String labeltxt;
int maxvalue;
TextInputType keyboardtype;
TextEditingController text;
bool _validate = false;
#override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
TextFormField(
controller: text,
cursorColor: Colors.black,
//textAlign: TextAlign.left,
// autocorrect: true,
// textInputAction: TextInputAction.go,
// maxLines: maxvalue,
// autofocus: true,
style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
textAlignVertical: TextAlignVertical.center,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(
RegExp('[a-z A-Z 0-9 #?!#%^&* ? # ^_ . : ! | "" \'-]')),
],
decoration: InputDecoration(
border: new UnderlineInputBorder(
// borderRadius: new BorderRadius.circular(5.0),
// borderSide: new BorderSide(),
),
hintText: hintValue,
labelText: labeltxt,
errorText: _validate ? 'Value Can\'t Be Empty' : null,
//prefixIcon: Icon(Icons),
//suffixIcon: Icon(Icons.currency_bitcoin)
),
keyboardType: keyboardtype,
validator: (value) {
if (value!.isEmpty) {
return "Value Can't be empty.";
}
return null;
},
),
],
),
);
}
}

Receiving Null check operator used on a null value error

I've been facing errors regarding my Syncfusion Calendar. Just recently, I was not able to initialize my _startDate and _endDate variables but some people suggested to make it nullable which I did but now it is giving me "Null check operator used on a null value" error.
Calendar Code:
class EventCalendar extends StatefulWidget {
const EventCalendar({Key? key}) : super(key: key);
#override
EventCalendarState createState() => EventCalendarState();
}
List<Color> _colorCollection = <Color>[];
List<String> _colorNames = <String>[];
int _selectedColorIndex = 0;
late DataSource _events;
Meeting? _selectedAppointment;
DateTime? _startDate;
DateTime? _endDate;
late TimeOfDay _startTime;
late TimeOfDay _endTime;
bool _isAllDay = false;
String _subject = '';
String _notes = '';
class EventCalendarState extends State<EventCalendar> {
EventCalendarState(); //check
CalendarView _calendarView = CalendarView.month;
late List<String> eventNameCollection;
late List<Meeting> appointments;
#override
void initState() {
_calendarView = CalendarView.month;
appointments = getMeetingDetails();
_events = DataSource(appointments);
_selectedAppointment = null;
_selectedColorIndex = 0;
_subject = '';
_notes = '';
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: UserDrawer(),
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
title: const Text('Itinerary',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: Colors.black)),
),
resizeToAvoidBottomInset: false,
body: Padding(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 5),
child: getEventCalendar(_calendarView, _events)),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add, color: Colors.white),
backgroundColor: Color(0xFF003893),
onPressed: () => Navigator.push<Widget>(
context,
MaterialPageRoute(
builder: (BuildContext context) => EventEditor()),
)));
}
SfCalendar getEventCalendar(
CalendarView _calendarView,
CalendarDataSource _calendarDataSource,
) {
return SfCalendar(
view: _calendarView,
backgroundColor: Colors.transparent,
initialSelectedDate: DateTime.now(),
todayHighlightColor: Color(0xFF003893),
selectionDecoration: BoxDecoration(color: Colors.white60),
showNavigationArrow: true,
cellBorderColor: Colors.transparent,
firstDayOfWeek: 1,
allowedViews: [
CalendarView.day,
CalendarView.week,
CalendarView.month,
CalendarView.timelineWeek
],
monthViewSettings: MonthViewSettings(
showAgenda: true,
agendaViewHeight: 250,
appointmentDisplayMode: MonthAppointmentDisplayMode.appointment),
dataSource: _calendarDataSource,
initialDisplayDate: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day, 0, 0, 0),
timeSlotViewSettings: TimeSlotViewSettings(
minimumAppointmentDuration: const Duration(minutes: 60)),
);
}
void onCalendarViewChange(String value) {
if (value == 'Day') {
_calendarView = CalendarView.day;
} else if (value == 'Week') {
_calendarView = CalendarView.week;
} else if (value == 'Month') {
_calendarView = CalendarView.month;
} else if (value == 'Timeline week') {
_calendarView = CalendarView.timelineWeek;
}
setState(() {});
}
List<Meeting> getMeetingDetails() {
final List<Meeting> meetingCollection = <Meeting>[];
eventNameCollection = <String>[];
eventNameCollection.add('');
_colorCollection = <Color>[];
_colorCollection.add(const Color(0xFF3D4FB5));
_colorCollection.add(const Color(0xFF0F8644));
_colorCollection.add(const Color(0xFF8B1FA9));
_colorCollection.add(const Color(0xFFD20100));
_colorCollection.add(const Color(0xFFFC571D));
_colorCollection.add(const Color(0xFF85461E));
_colorCollection.add(const Color(0xFFFF00FF));
_colorCollection.add(const Color(0xFFE47C73));
_colorCollection.add(const Color(0xFF636363));
_colorNames = <String>[];
_colorNames.add('Blue');
_colorNames.add('Green');
_colorNames.add('Purple');
_colorNames.add('Red');
_colorNames.add('Orange');
_colorNames.add('Caramel');
_colorNames.add('Magenta');
_colorNames.add('Peach');
_colorNames.add('Gray');
return meetingCollection;
}
}
class DataSource extends CalendarDataSource {
DataSource(List<Meeting> source) {
appointments = source;
}
#override
bool isAllDay(int index) => appointments![index].isAllDay;
#override
String getSubject(int index) => appointments![index].eventName;
#override
String getNotes(int index) => appointments![index].description;
#override
Color getColor(int index) => appointments![index].background;
#override
DateTime getStartTime(int index) => appointments![index].from;
#override
DateTime getEndTime(int index) => appointments![index].to;
}
class Meeting {
Meeting(
{required this.from,
required this.to,
this.background = Colors.green,
this.isAllDay = false,
this.eventName = '',
this.description = ''});
final String eventName;
final DateTime from;
final DateTime to;
final Color background;
final bool isAllDay;
final String description;
}
Add/Edit/Delete Event in Calendar Code:
class EventEditorState extends State<EventEditor> {
Widget _getAppointmentEditor(BuildContext context) {
return Container(
color: Colors.white,
child: ListView(
padding: const EdgeInsets.all(12),
children: <Widget>[
ListTile(
contentPadding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
title: TextFormField(
controller: TextEditingController(text: _subject),
onChanged: (String value) {
_subject = value;
},
keyboardType: TextInputType.multiline,
maxLines: null,
style: TextStyle(
fontSize: 15,
color: Colors.black,
fontWeight: FontWeight.w400),
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Title',
),
),
),
const Divider(
height: 1.0,
thickness: 1,
),
ListTile(
contentPadding: const EdgeInsets.all(5),
leading: Icon(
Icons.subject,
color: Colors.black87,
),
title: TextField(
controller: TextEditingController(text: _notes),
onChanged: (String value) {
_notes = value;
},
keyboardType: TextInputType.multiline,
maxLines: null,
style: TextStyle(
fontSize: 15,
color: Colors.black87,
fontWeight: FontWeight.w400),
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Add description',
),
),
),
const Divider(
height: 1.0,
thickness: 1,
),
ListTile(
contentPadding: const EdgeInsets.fromLTRB(10, 15, 20, 2),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('From', style: TextStyle(fontWeight: FontWeight.w500)),
SizedBox(height: 5),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
flex: 7,
child: GestureDetector(
child: Text(
DateFormat('EEE, MMM dd yyyy')
.format(_startDate!),
textAlign: TextAlign.left),
onTap: () async {
final DateTime? date = await showDatePicker(
context: context,
initialDate: _startDate!,
firstDate: DateTime(1900),
lastDate: DateTime(2100),
);
if (date != null && date != _startDate) {
setState(() {
final Duration difference =
_endDate!.difference(_startDate!);
_startDate = DateTime(
date.year,
date.month,
date.day,
_startTime.hour,
_startTime.minute,
0);
_endDate = _startDate!.add(difference);
_endTime = TimeOfDay(
hour: _endDate!.hour,
minute: _endDate!.minute);
});
}
}),
),
Expanded(
flex: 3,
child: _isAllDay
? const Text('')
: GestureDetector(
child: Text(
DateFormat('hh:mm a')
.format(_startDate!),
textAlign: TextAlign.right,
),
onTap: () async {
final TimeOfDay? time =
await showTimePicker(
context: context,
initialTime: TimeOfDay(
hour: _startTime.hour,
minute: _startTime.minute));
if (time != null &&
time != _startTime) {
setState(() {
_startTime = time;
final Duration difference =
_endDate!
.difference(_startDate!);
_startDate = DateTime(
_startDate!.year,
_startDate!.month,
_startDate!.day,
_startTime.hour,
_startTime.minute,
0);
_endDate =
_startDate!.add(difference);
_endTime = TimeOfDay(
hour: _endDate!.hour,
minute: _endDate!.minute);
});
}
})),
]),
],
)),
ListTile(
contentPadding: const EdgeInsets.fromLTRB(10, 5, 20, 2),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('To', style: TextStyle(fontWeight: FontWeight.w500)),
SizedBox(height: 5),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
flex: 7,
child: GestureDetector(
child: Text(
DateFormat('EEE, MMM dd yyyy')
.format(_endDate!),
textAlign: TextAlign.left,
),
onTap: () async {
final DateTime? date = await showDatePicker(
context: context,
initialDate: _endDate!,
firstDate: DateTime(1900),
lastDate: DateTime(2100),
);
if (date != null && date != _endDate) {
setState(() {
final Duration difference =
_endDate!.difference(_startDate!);
_endDate = DateTime(
date.year,
date.month,
date.day,
_endTime.hour,
_endTime.minute,
0);
if (_endDate!.isBefore(_startDate!)) {
_startDate =
_endDate!.subtract(difference);
_startTime = TimeOfDay(
hour: _startDate!.hour,
minute: _startDate!.minute);
}
});
}
}),
),
Expanded(
flex: 3,
child: _isAllDay
? const Text('')
: GestureDetector(
child: Text(
DateFormat('hh:mm a').format(_endDate!),
textAlign: TextAlign.right,
),
onTap: () async {
final TimeOfDay? time =
await showTimePicker(
context: context,
initialTime: TimeOfDay(
hour: _endTime.hour,
minute: _endTime.minute));
if (time != null && time != _endTime) {
setState(() {
_endTime = time;
final Duration difference =
_endDate!
.difference(_startDate!);
_endDate = DateTime(
_endDate!.year,
_endDate!.month,
_endDate!.day,
_endTime.hour,
_endTime.minute,
0);
if (_endDate!
.isBefore(_startDate!)) {
_startDate = _endDate!
.subtract(difference);
_startTime = TimeOfDay(
hour: _startDate!.hour,
minute: _startDate!.minute);
}
});
}
})),
]),
],
)),
SizedBox(height: 10),
ListTile(
contentPadding: const EdgeInsets.fromLTRB(10, 5, 20, 2),
leading: Icon(
Icons.access_time,
color: Colors.black54,
),
title: Row(children: <Widget>[
const Expanded(
child: Text('All-day'),
),
Expanded(
child: Align(
alignment: Alignment.centerRight,
child: Switch(
value: _isAllDay,
onChanged: (bool value) {
setState(() {
_isAllDay = value;
});
},
))),
])),
const Divider(
height: 1.0,
thickness: 1,
),
ListTile(
contentPadding: const EdgeInsets.fromLTRB(10, 5, 20, 2),
leading: Icon(Icons.lens,
color: _colorCollection[_selectedColorIndex]),
title: Text(
_colorNames[_selectedColorIndex],
),
onTap: () {
showDialog<Widget>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return _ColorPicker();
},
).then((dynamic value) => setState(() {}));
},
),
const Divider(
height: 1.0,
thickness: 1,
),
],
));
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text(getTile()),
backgroundColor: _colorCollection[_selectedColorIndex],
leading: IconButton(
icon: const Icon(
Icons.close,
color: Colors.white,
),
onPressed: () {
Navigator.pop(context);
},
),
actions: <Widget>[
IconButton(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
icon: const Icon(
Icons.done,
color: Colors.white,
),
onPressed: () {
final List<Meeting> meetings = <Meeting>[];
if (_selectedAppointment != null) {
_events.appointments!.removeAt(_events.appointments!
.indexOf(_selectedAppointment));
_events.notifyListeners(CalendarDataSourceAction.remove,
<Meeting>[]..add(_selectedAppointment!));
}
meetings.add(Meeting(
from: _startDate!,
to: _endDate!,
background: _colorCollection[_selectedColorIndex],
description: _notes,
isAllDay: _isAllDay,
eventName: _subject == '' ? '(No Title)' : _subject,
));
_events.appointments!.add(meetings[0]);
_events.notifyListeners(
CalendarDataSourceAction.add, meetings);
_selectedAppointment = null;
Navigator.pop(context);
})
],
),
body: Padding(
padding: const EdgeInsets.fromLTRB(5, 5, 5, 5),
child: Stack(
children: <Widget>[_getAppointmentEditor(context)],
),
),
floatingActionButton: _selectedAppointment == null
? const Text('')
: FloatingActionButton(
onPressed: () {
if (_selectedAppointment != null) {
_events.appointments!.removeAt(_events.appointments!
.indexOf(_selectedAppointment));
_events.notifyListeners(CalendarDataSourceAction.remove,
<Meeting>[]..add(_selectedAppointment!));
_selectedAppointment = null;
Navigator.pop(context);
}
},
child:
const Icon(Icons.delete_outline, color: Colors.white),
backgroundColor: Colors.red,
)));
}
String getTile() {
return _subject.isEmpty ? 'New event' : 'Event details';
}
}
How do I solve this issue?

The method 'getUsers' was called on null. Receiver: null Tried calling: getUsers()

I am getting error on red screen right after i run my app. My first screen is login screen. I want to simply register the user and login the user. but when i use the getUsers() or getLogin() I get the above error. I am fed up of this error. Searched everywhere but m not able to find any working solutions. Please can u please write the code which i need to add. Please help me.
UserLogin.dart
import 'dart:ui';
import 'package:customer/models/registerUser.dart';
import 'package:customer/screens/UserRegistration.dart';
import 'package:customer/screens/people_list.dart';
import 'package:customer/services/db_service.dart';
import 'package:customer/utils/form_helper.dart';
import 'package:flutter/material.dart';
import 'ForgotPassword.dart';
class UserLogin extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return UserLoginState();
}
}
class UserLoginState extends State<UserLogin>{
final reguser = RegisterUser();
String name,_password,_email;
var _formKey=GlobalKey<FormState>();
RegisterUser model;
DBService dbService;
var _minimumPadding = 5.0;
TextEditingController usernameController=TextEditingController();
TextEditingController passwordController=TextEditingController();
bool isHiddenPassword=true;
final scaffoldKey = new GlobalKey<ScaffoldState>();
void _showSnackBar(String text) {
scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Text(text),
));
}
void _togglePasswordView() {
setState(() {
isHiddenPassword = !isHiddenPassword;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Customer Tracking System'),),
body:_fetchData(),
);
}
Widget _fetchData(){
return FutureBuilder<List<RegisterUser>>(
future: dbService.getUsers(),
builder:
(BuildContext context, AsyncSnapshot<List<RegisterUser>> userDetails) {
if (userDetails.hasData) {
return _loginUI(userDetails.data);
}
return CircularProgressIndicator();
},
);
}
Widget _loginUI(List<RegisterUser> userDetails){
TextStyle textStyle = Theme.of(context).textTheme.title;
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
Form(
key: _formKey,
child: Container(
child: Padding(
padding: EdgeInsets.all(_minimumPadding * 2),
child: ListView
(
children: <Widget>[
Text("Login".toUpperCase(),
style: TextStyle(
fontSize: 40.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
SizedBox(height: height * 0.08,),
Divider(),
Padding(
padding: EdgeInsets.only(
top: _minimumPadding * 3,
bottom: _minimumPadding),
child: TextFormField(
controller: usernameController,
style: textStyle,
validator: (String value) {
if (value.isEmpty) {
return 'Please Enter Name';
}
return null;
},
onSaved: (String value) {
_email = value;
},
decoration: InputDecoration(
// filled: true,
//fillColor: Colors.white,
prefixIcon: Icon(Icons.person),
labelText: 'Username',
hintText: 'Username',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0)
)
)
)),
Padding(
padding: EdgeInsets.only(
top: _minimumPadding * 3,
bottom: _minimumPadding),
child: TextFormField(
style: textStyle,
obscureText: isHiddenPassword,
controller: passwordController,
validator: (String value) {
if (value.isEmpty) {
return 'Please Enter Name';
}
return null;
},
onSaved: (String value) {
_password = value;
},
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock),
suffixIcon: InkWell(
onTap: _togglePasswordView,
child: Icon(Icons.visibility)),
labelText: 'Password',
hintText: 'Password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0)
)
)
)
),
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ForgotPassword()));
},
child: Text(
"Forgot Password ?",
style: TextStyle(
fontSize: 18,
color: Colors.purpleAccent,
//fontWeight: FontWeight.bold,
letterSpacing: 1.7),
textAlign: TextAlign.right,
),
),
SizedBox(
height: height * 0.08,
),
GestureDetector(
onTap: () {
_submit();
},
child: Container(
padding:
EdgeInsets.symmetric(horizontal: 26, vertical: 20),
decoration: BoxDecoration(
//gradient: new LinearGradient(
//colors: [Colors.purple, Colors.purpleAccent]),
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
blurRadius: 4,
//color: Colors.purpleAccent,
offset: Offset(2, 2))
]),
child: Text(
"Login".toUpperCase(),
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
letterSpacing: 1.7),
textAlign: TextAlign.center,
),
),
),
SizedBox(
height: height * 0.05,
),
SizedBox(
height: height * 0.05,
),
Row(
children: <Widget>[
Expanded(
child: Text("Not yet registered?",
style: TextStyle(
fontSize: 25.0)
)
),
GestureDetector(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => UserRegistration()));
},
child: Center(
child: Container(
padding:
EdgeInsets.symmetric(
horizontal: 26, vertical: 10),
decoration: BoxDecoration(
//gradient: new LinearGradient(
// colors: [Colors.purple, Colors.purpleAccent]),
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
blurRadius: 4,
//color:,
offset: Offset(2, 2))
]),
child: Text(
"Register".toUpperCase(),
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
letterSpacing: 1.7),
textAlign: TextAlign.center,
),
),
),
)
],
),
],
)),
),
);
}
bool validateAndSave() {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
void _submit(){
final form = _formKey.currentState;
var res;
if (validateAndSave()) {
setState(() {
//getLogin(_email, _password);
res=dbService.getLogin(_email, _password).then((value) {
if(res!=0){
FormHelper.showMessage(
context,
"Login",
"Login Successfull",
"Ok",
() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => People_List(),
),
);
},
);}
else {
FormHelper.showMessage(
context,
"Login",
"Login not Successfull",
"Ok", () {}
);
}
});
});
}
}
}
RegisterUser.dart
import 'model.dart';
class RegisterUser extends Model {
static String table = 'userDetails';
int id;
String firstName;
String lastName;
String mobileNum;
String emailId;
String address;
String userType;
String password;
RegisterUser({
this.id,
this.firstName,
this.lastName,
this.mobileNum,
this.emailId,
this.address,
this.userType,
this.password
});
static RegisterUser fromMap(Map<String, dynamic> map) {
return RegisterUser(
id: map["id"],
firstName: map['firstName'].toString(),
lastName: map['lastName'],
mobileNum: map['mobileNum'],
emailId: map['emailId'],
address: map['address'],
userType: map['userType'],
password: map['password']
);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'id': id,
'firstName': firstName,
'lastName': lastName,
'mobileNum': mobileNum,
'emailId': emailId,
'address': address,
'userType':userType,
'password':password
};
if (id != null) {
map['id'] = id;
}
return map;
}
}
db_service.dart
import 'package:customer/models/registerUser.dart';
import 'package:customer/utils/database_helper.dart';
Future<List<RegisterUser>> getUsers() async {
await DB.init();
List<Map<String, dynamic>> userDetails = await DB.query(RegisterUser.table);
return userDetails.map((item) => RegisterUser.fromMap(item)).toList();
}
Future<List<RegisterUser>> getLogin(String email, String password) async {
await DB.init();
List<Map<String, dynamic>> res = await DB.rawQuery("SELECT * FROM userDetails WHERE emailId = '$email' and password = '$password'");
if (res.length > 0) {
return res.map((item) => RegisterUser.fromMap(item)).toList();
//return new User.fromMap(res.first);
}
return null;
}
You need a line with dbService = something before you can do dbService.getUsers() because just saying DbService dbService; initializes it to be null.
It's like a paper with no phone number on it and you are trying to call someone with it. You need to write down a phone number on it.
I finally got the answer to my question.
I had to just instantiate the DBService.
i.e DBService dbService=new DBService();
class UserLoginState extends State<UserLogin>{
final reguser = RegisterUser();
String name,_password,_email;
var _formKey=GlobalKey<FormState>();
RegisterUser model;
DBService dbService=new DBService();
...