Not able to remove focus from input field - flutter

I have four textfields, a title field, a details field, a date field, and a time field. Both the date and time fields are wrapped within a gesture detector, and onTap calls a pickDateAndTime method. The problem is that when I click on the date field and try to manually change the time through the input rather than the dial way, the focus goes to the title field and when I am still on the time picker and type something in the time picker, the title field gets changed with the new input. The weird part is that this error just appeared out of nowhere, and there are no errors reported in the console.
class TodoScreen extends StatefulWidget {
final int? todoIndex;
final int? arrayIndex;
const TodoScreen({Key? key, this.todoIndex, this.arrayIndex})
: super(key: key);
#override
State<TodoScreen> createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
final ArrayController arrayController = Get.find();
final AuthController authController = Get.find();
final String uid = Get.find<AuthController>().user!.uid;
late TextEditingController _dateController;
late TextEditingController _timeController;
late TextEditingController titleEditingController;
late TextEditingController detailEditingController;
late String _setTime, _setDate;
late String _hour, _minute, _time;
late String dateTime;
late bool done;
#override
void initState() {
super.initState();
String title = '';
String detail = '';
String date = '';
String? time = '';
if (widget.todoIndex != null) {
title = arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].title ??
'';
detail = arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].details ??
'';
date = arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].date!;
time = arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].time;
}
_dateController = TextEditingController(text: date);
_timeController = TextEditingController(text: time);
titleEditingController = TextEditingController(text: title);
detailEditingController = TextEditingController(text: detail);
done = (widget.todoIndex == null)
? false
: arrayController
.arrays[widget.arrayIndex!].todos![widget.todoIndex!].done!;
}
DateTime selectedDate = DateTime.now();
TimeOfDay selectedTime = TimeOfDay(
hour: (TimeOfDay.now().minute > 55)
? TimeOfDay.now().hour + 1
: TimeOfDay.now().hour,
minute: (TimeOfDay.now().minute > 55) ? 0 : TimeOfDay.now().minute + 5);
Future<DateTime?> _selectDate() => showDatePicker(
builder: (context, child) {
return datePickerTheme(child);
},
initialEntryMode: DatePickerEntryMode.calendarOnly,
context: context,
initialDate: selectedDate,
initialDatePickerMode: DatePickerMode.day,
firstDate: DateTime.now(),
lastDate: DateTime(DateTime.now().year + 5));
Future<TimeOfDay?> _selectTime() => showTimePicker(
builder: (context, child) {
return timePickerTheme(child);
},
context: context,
initialTime: selectedTime,
initialEntryMode: TimePickerEntryMode.input);
Future _pickDateTime() async {
DateTime? date = await _selectDate();
if (date == null) return;
if (date != null) {
selectedDate = date;
_dateController.text = DateFormat("MM/dd/yyyy").format(selectedDate);
}
TimeOfDay? time = await _selectTime();
if (time == null) {
_timeController.text = formatDate(
DateTime(
DateTime.now().year,
DateTime.now().day,
DateTime.now().month,
DateTime.now().hour,
DateTime.now().minute + 5),
[hh, ':', nn, " ", am]).toString();
}
if (time != null) {
selectedTime = time;
_hour = selectedTime.hour.toString();
_minute = selectedTime.minute.toString();
_time = '$_hour : $_minute';
_timeController.text = _time;
_timeController.text = formatDate(
DateTime(2019, 08, 1, selectedTime.hour, selectedTime.minute),
[hh, ':', nn, " ", am]).toString();
}
}
#override
Widget build(BuildContext context) {
bool visible =
(_dateController.text.isEmpty && _timeController.text.isEmpty)
? false
: true;
final formKey = GlobalKey<FormState>();
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text((widget.todoIndex == null) ? 'New Task' : 'Edit Task',
style: menuTextStyle),
leadingWidth: (MediaQuery.of(context).size.width < 768) ? 90.0 : 100.0,
leading: Center(
child: Padding(
padding: (MediaQuery.of(context).size.width < 768)
? const EdgeInsets.only(left: 0)
: const EdgeInsets.only(left: 21.0),
child: TextButton(
style: const ButtonStyle(
splashFactory: NoSplash.splashFactory,
),
onPressed: () {
Get.back();
},
child: Text(
"Cancel",
style: paragraphPrimary,
),
),
),
),
centerTitle: true,
actions: [
Center(
child: Padding(
padding: (MediaQuery.of(context).size.width < 768)
? const EdgeInsets.only(left: 0)
: const EdgeInsets.only(right: 21.0),
child: TextButton(
style: const ButtonStyle(
splashFactory: NoSplash.splashFactory,
),
onPressed: () async {
},
child: Text((widget.todoIndex == null) ? 'Add' : 'Update',
style: paragraphPrimary),
),
),
)
],
),
body: SafeArea(
child: Container(
width: double.infinity,
padding: (MediaQuery.of(context).size.width < 768)
? const EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0)
: const EdgeInsets.symmetric(horizontal: 35.0, vertical: 15.0),
child: Column(
children: [
Form(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
validator: Validator.titleValidator,
controller: titleEditingController,
autofocus: true, // problem here
autocorrect: false,
cursorColor: Colors.grey,
maxLines: 1,
maxLength: 25,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
counterStyle: counterTextStyle,
hintStyle: hintTextStyle,
hintText: "Title",
border: InputBorder.none),
style: todoScreenStyle),
primaryDivider,
TextField(
controller: detailEditingController,
maxLines: null,
autocorrect: false,
cursorColor: Colors.grey,
textInputAction: TextInputAction.done,
decoration: InputDecoration(
counterStyle: counterTextStyle,
hintStyle: hintTextStyle,
hintText: "Notes",
border: InputBorder.none),
style: todoScreenDetailsStyle),
],
),
),
Visibility(
visible: (widget.todoIndex != null) ? true : false,
child: GestureDetector(
onTap: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Completed",
style: todoScreenStyle,
),
Transform.scale(
scale: 1.3,
child: Theme(
data: ThemeData(
unselectedWidgetColor: const Color.fromARGB(
255, 187, 187, 187)),
child: Checkbox(
shape: const CircleBorder(),
checkColor: Colors.white,
activeColor: primaryColor,
value: done,
side: Theme.of(context).checkboxTheme.side,
onChanged: (value) {
setState(() {
done = value!;
});
})),
)
],
),
),
),
GestureDetector(
onTap: () async {
await _pickDateTime();
setState(() {
visible = true;
});
},
child: Column(
children: [
Row(
children: [
Flexible(
child: TextField(
enabled: false,
controller: _dateController,
onChanged: (String val) {
_setDate = val;
},
decoration: InputDecoration(
hintText: "Date",
hintStyle: hintTextStyle,
border: InputBorder.none),
style: todoScreenStyle,
),
),
visible
? IconButton(
onPressed: () {
_dateController.clear();
_timeController.clear();
setState(() {});
},
icon: const Icon(
Icons.close,
color: Colors.white,
))
: Container()
],
),
primaryDivider,
TextField(
onChanged: (String val) {
_setTime = val;
},
enabled: false,
controller: _timeController,
decoration: InputDecoration(
hintText: "Time",
hintStyle: hintTextStyle,
border: InputBorder.none),
style: todoScreenStyle,
)
],
),
),
],
),
),
),
);
}
}
Should I open an issue on Github, as I had not made any changes to the code for it behave this way and also because there were no errors in the console
Here is the full code on Github
Update
Here is a reproducible example:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const TodoScreen(),
);
}
}
class TodoScreen extends StatefulWidget {
const TodoScreen({Key? key}) : super(key: key);
#override
State<TodoScreen> createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
late TextEditingController _dateController;
late TextEditingController _timeController;
late TextEditingController titleEditingController;
late TextEditingController detailEditingController;
late String _setTime, _setDate;
late String _hour, _minute, _time;
late String dateTime;
#override
void initState() {
super.initState();
String title = '';
String detail = '';
String date = '';
String? time = '';
_dateController = TextEditingController(text: date);
_timeController = TextEditingController(text: time);
titleEditingController = TextEditingController(text: title);
detailEditingController = TextEditingController(text: detail);
}
#override
void dispose() {
super.dispose();
titleEditingController.dispose();
detailEditingController.dispose();
_timeController.dispose();
_dateController.dispose();
}
Theme timePickerTheme(child) => Theme(
data: ThemeData.dark().copyWith(
timePickerTheme: TimePickerThemeData(
backgroundColor: const Color.fromARGB(255, 70, 70, 70),
dayPeriodTextColor: Colors.green,
hourMinuteTextColor: MaterialStateColor.resolveWith((states) =>
states.contains(MaterialState.selected)
? Colors.white
: Colors.white),
dialHandColor: Colors.green,
helpTextStyle: TextStyle(
fontSize: 12, fontWeight: FontWeight.bold, color: Colors.green),
dialTextColor: MaterialStateColor.resolveWith((states) =>
states.contains(MaterialState.selected)
? Colors.white
: Colors.white),
entryModeIconColor: Colors.green,
),
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
foregroundColor:
MaterialStateColor.resolveWith((states) => Colors.green)),
),
),
child: child!,
);
Theme datePickerTheme(child) => Theme(
data: ThemeData.dark().copyWith(
colorScheme: ColorScheme.dark(
surface: Colors.green,
secondary: Colors.green,
onPrimary: Colors.white,
onSurface: Colors.white,
primary: Colors.green,
)),
child: child!,
);
DateTime selectedDate = DateTime.now();
TimeOfDay selectedTime = TimeOfDay(
hour: (TimeOfDay.now().minute > 55)
? TimeOfDay.now().hour + 1
: TimeOfDay.now().hour,
minute: (TimeOfDay.now().minute > 55) ? 0 : TimeOfDay.now().minute + 5);
Future<DateTime?> _selectDate() => showDatePicker(
builder: (context, child) {
return datePickerTheme(child);
},
initialEntryMode: DatePickerEntryMode.calendarOnly,
context: context,
initialDate: selectedDate,
initialDatePickerMode: DatePickerMode.day,
firstDate: DateTime.now(),
lastDate: DateTime(DateTime.now().year + 5));
Future<TimeOfDay?> _selectTime() => showTimePicker(
builder: (context, child) {
return timePickerTheme(child);
},
context: context,
initialTime: selectedTime,
initialEntryMode: TimePickerEntryMode.input);
Future _pickDateTime() async {
DateTime? date = await _selectDate();
if (date == null) return;
if (date != null) {
selectedDate = date;
_dateController.text = selectedDate.toString();
}
TimeOfDay? time = await _selectTime();
if (time != null) {
selectedTime = time;
_hour = selectedTime.hour.toString();
_minute = selectedTime.minute.toString();
_time = '$_hour : $_minute';
_timeController.text = _time;
_timeController.text =
DateTime(2019, 08, 1, selectedTime.hour, selectedTime.minute)
.toString();
}
}
#override
Widget build(BuildContext context) {
bool visible =
(_dateController.text.isEmpty && _timeController.text.isEmpty)
? false
: true;
final formKey = GlobalKey<FormState>();
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
centerTitle: true,
),
body: SafeArea(
child: Container(
width: double.infinity,
padding: (MediaQuery.of(context).size.width < 768)
? const EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0)
: const EdgeInsets.symmetric(horizontal: 35.0, vertical: 15.0),
child: Column(
children: [
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(14.0)),
padding: const EdgeInsets.symmetric(
horizontal: 24.0, vertical: 15.0),
child: Form(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: titleEditingController,
autofocus: true,
autocorrect: false,
cursorColor: Colors.grey,
maxLines: 1,
maxLength: 25,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
hintText: "Title", border: InputBorder.none),
),
Divider(color: Colors.black),
TextField(
controller: detailEditingController,
maxLines: null,
autocorrect: false,
cursorColor: Colors.grey,
textInputAction: TextInputAction.done,
decoration: InputDecoration(
hintText: "Notes", border: InputBorder.none),
),
],
),
)),
GestureDetector(
onTap: () async {
await _pickDateTime();
setState(() {
visible = true;
});
},
child: Container(
margin: const EdgeInsets.only(top: 20.0),
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 24.0, vertical: 15.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14.0)),
child: Column(
children: [
Row(
children: [
Flexible(
child: TextField(
enabled: false,
controller: _dateController,
onChanged: (String val) {
_setDate = val;
},
decoration: InputDecoration(
hintText: "Date", border: InputBorder.none),
),
),
visible
? IconButton(
onPressed: () {
_dateController.clear();
_timeController.clear();
setState(() {});
},
icon: const Icon(
Icons.close,
color: Colors.white,
))
: Container()
],
),
Divider(
color: Colors.blue,
),
TextField(
onChanged: (String val) {
_setTime = val;
},
enabled: false,
controller: _timeController,
decoration: InputDecoration(
hintText: "Enter", border: InputBorder.none),
)
],
)),
),
],
),
),
),
);
}
}

In your main.dart file, you should return something like this:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
// This allows closing keyboard when tapping outside of a text field
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus &&
currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus!.unfocus();
}
},
child: // your app's entry point,
);
}
}

Add a focusNode in your textField:
FocusNode focusNode = FocusNode();
TextField(
focusNode: focusNode,
);
And then in the gesture detector, add that following code to unselect the textfield input:
FocusScope.of(context).requestFocus(FocusNode());

simply wrap your Scaffold widget GestureDetector and add FocusScope.of(context).requestFocus(FocusNode()); it will automatically unfocused text field when you click anywhere on your screen
GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Scaffold()
)

You can use below code to remove focus in gesture detector event
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
currentFocus.unfocus();
}

Related

buildScope missed some dirty elements in flutter

enter image description here
I have error like above picture. what is buildscope. I think it is related with lifecycle. I cannot find where is problem. I think that it doesn't use dispose so it show error. but it is not correct. PincodeTextField widget automatically do dispose. what is problem in my code.
class PinSettingScreen extends StatefulWidget {
const PinSettingScreen({Key? key}) : super(key: key);
#override
State<PinSettingScreen> createState() => _PinSettingScreenState();
}
class _PinSettingScreenState extends State<PinSettingScreen> {
late FlutterSecureStorage _storage;
late MethodChannel _finPongChannel;
late TextEditingController _inputEditingController;
late String _pinNo;
late Map _userData;
late FocusNode _inputPinFocusNode;
bool _isCompleted = false;
#override
void initState() {
super.initState();
_storage = const FlutterSecureStorage();
_inputEditingController = TextEditingController();
_inputPinFocusNode = FocusNode();
_finPongChannel = const MethodChannel("io.codef.finpong");
_finPongChannel.setMethodCallHandler(closeFinPong);
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
_userData = context.currentBeamLocation.data as Map;
}
Future<void> closeFinPong(MethodCall call) async {
if (call.method == "closeFinPong") {
Provider.of<AuthenticationNotifier>(context, listen: false)
.setUserAuth(true);
}
}
Widget _pinInputPage() {
return Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"헤이홀더에서 사용할",
style: TextStyle(
color: Colors.black,
fontSize: 20.0.sp,
fontWeight: FontWeight.w500),
),
SizedBox(
height: 5.0.h,
),
Text("비밀번호를 입력해주세요.",
style: TextStyle(
color: Colors.black,
fontSize: 20.0.sp,
fontWeight: FontWeight.w500)),
SizedBox(
height: 30.0.h,
),
PinCodeTextField(
appContext: context,
length: 6,
keyboardType: TextInputType.number,
obscureText: true,
autoFocus: true,
blinkWhenObscuring: true,
focusNode: _inputPinFocusNode,
controller: _inputEditingController,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
onChanged: (value) {},
pinTheme: PinTheme(
shape: PinCodeFieldShape.box,
borderRadius: BorderRadius.circular(5)),
onCompleted: (value) {
setState(() {
_isCompleted = true;
_pinNo = _inputEditingController.text;
});
_inputEditingController.clear();
FocusScope.of(context).nextFocus();
},
)
],
),
),
);
}
Future<void> _signup() async {
showCircularProgressIndicator(context);
final authNotifier =
Provider.of<AuthenticationNotifier>(context, listen: false);
final fcmToken = await FirebaseMessaging.instance.getToken();
_userData.putIfAbsent("pinNo", () => _pinNo);
_userData.putIfAbsent("deviceId", () => fcmToken);
SignUpModel signUpResult = await AuthService().signUp(_userData);
if (signUpResult.ok!) {
final SharedPreferences pref = await SharedPreferences.getInstance();
await pref.setBool("useLock", true);
await _storage.write(
key: "userId", value: signUpResult.data?.userId.toString());
final userState = signUpResult.data?.userState;
if (userState == "new") {
final codefToken = signUpResult.data?.codefToken;
final arguments = {"codefToken": codefToken, "entry": "0"};
await _finPongChannel.invokeMethod("finpongStart", arguments);
} else {
authNotifier.setUserAuth(true);
}
} else {
//TODO://알수없는 에러 발생.
}
}
Widget _pinCheckPage() {
return Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"비밀번호 확인을 위해",
style: TextStyle(
color: Colors.black,
fontSize: 20.0.sp,
fontWeight: FontWeight.w500),
),
SizedBox(
height: 5.0.h,
),
Text(
"다시 한번 입력해주세요.",
style: TextStyle(
color: Colors.black,
fontSize: 20.0.sp,
fontWeight: FontWeight.w500),
),
SizedBox(
height: 30.0.h,
),
PinCodeTextField(
appContext: context,
length: 6,
keyboardType: TextInputType.number,
obscureText: true,
blinkWhenObscuring: true,
onChanged: (value) {},
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
pinTheme: PinTheme(
shape: PinCodeFieldShape.box,
borderRadius: BorderRadius.circular(5)),
validator: (value) {
if (value!.length == 6 && _pinNo != value) {
return "이전 입력 값과 다른 값을 입력하였습니다.";
} else {
return null;
}
},
onCompleted: (value) async {
if (_pinNo == value) {
await _signup();
}
},
)
],
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _isCompleted
? AppBar(
elevation: 0,
backgroundColor: Colors.white,
leadingWidth: 38.0.w,
leading: IconButton(
padding: EdgeInsets.only(left: 15.0.w),
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.black,
),
onPressed: () {
setState(() {
_pinNo = "";
_isCompleted = false;
});
_inputEditingController.clear();
FocusScope.of(context).requestFocus(_inputPinFocusNode);
},
),
)
: null,
body: _isCompleted ? _pinCheckPage() : _pinInputPage());
}
}

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;
},
),
],
),
);
}
}

How can I change the position of the Textformfield validation text ? Flutter

I made a custom form and when I want to use the validation. My issue is that the error message is not appearing as I wanted. Here's the screenshot of it.
So I want to change the position of the error message to be below my container. Does anyone have any idea how to do it ?
Here's the code of the form:
class AuthForm extends StatefulWidget {
final bool isPassword;
final IconData prefixIcon;
final String hintText;
late bool isPasswordVisible = isPassword;
final bool isCalendar;
final TextEditingController controller;
final bool isDropDown;
final bool isPhone;
final String? Function(String?)? validator;
AuthForm({Key? key, this.isPassword = false, required this.prefixIcon, required this.hintText,
this.isCalendar = false, required this.controller, this.isDropDown = false, this.isPhone = false, required this.validator}) : super(key: key);
#override
State<AuthForm> createState() => _AuthFormState();
}
class _AuthFormState extends State<AuthForm> {
#override
void initState() {
super.initState();
if (widget.isPhone){
getCountryCode();
}
}
start () async {
await CountryCodes.init();
}
Locale? getCountryCode () {
start();
final Locale? deviceLocale = CountryCodes.getDeviceLocale();
final CountryDetails details = CountryCodes.detailsForLocale();
return deviceLocale;
}
DateTime selectedDate = DateTime(2000,1);
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1950, 1),
lastDate: DateTime.now());
if (picked != null && picked != selectedDate) {
setState(() {
selectedDate = picked;
});
}
}
#override
Widget build(BuildContext context) {
return Container(
width: 70.w,
height: 5.h,
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
width: 0.13.w,
color: Theme.of(context).splashColor,
),
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(
widget.prefixIcon,
color: Theme.of(context).primaryColor,
size: 6.w,
),
widget.isDropDown ? const DropDownBar() :
Expanded(
child: TextFormField(
//autovalidateMode: AutovalidateMode.onUserInteraction,
validator: widget.validator,
keyboardType: widget.isPhone ? TextInputType.phone : TextInputType.text,
inputFormatters: [DialCodeFormatter()],
controller: widget.controller,
textAlign: TextAlign.center,
obscureText: widget.isPasswordVisible,
style: Theme.of(context).textTheme.bodyText2,
decoration: InputDecoration(
hintText : widget.hintText,
hintStyle: Theme.of(context).textTheme.bodyText1,
border: InputBorder.none,
),
onTap: () async {
if (widget.isCalendar){
//Dismiss the keyboard
FocusScope.of(context).requestFocus(FocusNode());
//Call the calendar
await _selectDate(context);
widget.controller.text = DateFormat('dd-MM-yyyy').format(selectedDate);
}
}
),
),
//Show Icon only if the form is for a Password
Visibility(
visible: widget.isPassword,
//Maintain the space where the widget is even if it is hid
maintainAnimation: true,
maintainState: true,
maintainSize: true,
child: InkWell(
highlightColor : Colors.transparent,
splashColor: Colors.transparent,
child: Icon(
widget.isPasswordVisible ? Icons.visibility : Icons.visibility_off,
color: Theme.of(context).primaryColor,
size: 6.w,
),
onTap: () {
setState(() {
widget.isPasswordVisible = !widget.isPasswordVisible;
});
},
),
),
],
),
);
}
}
Thanks for your suggestion,
Chris
You should try below piece of code for TextFormField
TextFormField(
textInputAction: TextInputAction.next,
style: TextStyle(fontSize: 16, height: 1),
inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(10)],
keyboardType: TextInputType.phone,
validator: (val) {
if (val!.isEmpty) {
return 'Please enter your mobile number';
} else if (val.length < 10) {
return 'Mobile number should be 10 digits only';
}
},
controller: bloc.mobileNumberLoginController,
decoration: InputDecoration(
filled: true,
border: OutlineInputBorder(
borderSide: BorderSide(
color: code != null ? HexColor(code!) : Colors.pink,
)),
contentPadding: EdgeInsets.only(top: 5, bottom: 5, left: 10, right: 10),
),
),

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?

getting error " getter 'year' was called on null " when clearing textfield in flutter

here when I click on the clear button it will not clear the all the textbox only clearing the expiry_date field only and also showing me the exception "getter year was called on null".
in this code I have a clear button when I click on that button it will not clearing the button and showing year called on null. I think this problem happens because I've added onChanged in ExpiryDate widget. but I need an onChnaged event. so I need to clear everything. Hope you understand the question. Your help can make my day.
Here is the code :
class _BspLicensedSignupPageState extends State<BspLicensedSignupPage>
with AfterLayoutMixin<BspLicensedSignupPage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController _bspBusinessLicenseNumber =
TextEditingController();
final TextEditingController _bspLicenseAuthorityName =
TextEditingController();
final TextEditingController _bspLicenseExpiryDate = TextEditingController();
final format = new DateFormat.yMMMEd('en-US');
String _isoDate;
List<BusinessProfilePicture> _bspLicenseImages =
new List<BusinessProfilePicture>();
List<Object> images = List<Object>();
List<dynamic> _bspLicenseAuthorityTypes = <dynamic>[];
Map<String, dynamic> _bspLicenseAuthorityType;
bool _isvisibleissuingauthority = false;
bool businesslicensecheck = false;
int radioValue = -1;
Future<File> licenceimage;
Future<File> profilepicture;
DateTime date;
TimeOfDay time;
String _countryId;
BSPSignupRepository _bspSignupRepository = new BSPSignupRepository();
bool autovalidate = false;
bool _isEditMode = false;
int selected = 0;
List<String> _imageFilesList = [];
var isUploadingPost = false;
var isEditInitialised = true;
List<File> _licenseImages = [];
#override
void initState() {
super.initState();
_scrollController = ScrollController();
}
Widget _buildbusinesslicenseno() {
return new TudoTextWidget(
prefixIcon: Icon(FontAwesomeIcons.idCard),
controller: _bspBusinessLicenseNumber,
labelText: AppConstantsValue.appConst['licensedsignup']
['businesslicenseno']['translation'],
validator: Validators().validateLicenseno,
);
}
Widget _buildexpirydate() {
return DateTimeField(
format: format,
autocorrect: true,
autovalidate: false,
controller: _bspLicenseExpiryDate,
readOnly: true,
validator: (date) => (date == null || _bspLicenseExpiryDate.text == '')
? 'Please enter valid date'
: null,
onChanged: (date) {
_isoDate = DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(date);
},
decoration: InputDecoration(
labelText: "Expiry Date",
hintText: "Expiry Date",
prefixIcon: Icon(
FontAwesomeIcons.calendar,
size: 24,
)),
onShowPicker: (context, currentValue) {
return showDatePicker(
context: context,
firstDate: DateTime.now(),
initialDate: currentValue ?? DateTime.now(),
lastDate: DateTime(2100),
);
},
);
}
Widget _buildlicenseauthority() {
return new TudoTextWidget(
validator: (val) => Validators.validateName(val, "Issuing Authority"),
controller: _bspLicenseAuthorityName,
prefixIcon: Icon(Icons.account_circle),
labelText: AppConstantsValue.appConst['licensedsignup']
['licenseissuingauthority']['translation'],
hintText: AppConstantsValue.appConst['licensedsignup']
['licenseissuingauthority']['translation'],
);
}
Widget _buildlabeluploadlicensepicture() {
return Text(AppConstantsValue.appConst['licensedsignup']
['labeluploadlicenpicture']['translation']);
}
Widget _buildlegalbusinesscheck() {
return TudoConditionWidget(
text: AppConstantsValue.appConst['licensedsignup']['legalbusinesscheck']
['translation'],
);
}
Widget content(
BuildContext context, BspLicensedSignupViewModel bspLicensedSignupVm) {
final appBar = AppBar(
centerTitle: true,
title: Text("BSP Licensed Details"),
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
NavigationHelper.navigatetoBack(context);
},
),
);
final bottomNavigationBar = Container(
height: 56,
//margin: EdgeInsets.symmetric(vertical: 24, horizontal: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FlatButton.icon(
icon: Icon(Icons.close),
label: Text('Clear'),
color: Colors.redAccent,
textColor: Colors.black,
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
// onpress
onPressed: () {
_formKey.currentState.reset();
_bspBusinessLicenseNumber.clear();
_bspLicenseAuthorityName.clear();
_bspBusinessLicenseNumber.text = '';
_bspLicenseAuthorityName.text = '';
setState(() {
_licenseImages.clear();
_imageFilesList.clear();
});
},
),
new FlatButton.icon(
icon: Icon(FontAwesomeIcons.arrowCircleRight),
label: Text('Next'),
color: colorStyles["primary"],
textColor: Colors.white,
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () async {
},
),
],
),
);
return new Scaffold(
appBar: appBar,
bottomNavigationBar: bottomNavigationBar,
body: Container(
height: double.infinity,
width: double.infinity,
child: Stack(
children: <Widget>[
// Background(),
SingleChildScrollView(
controller: _scrollController,
child: SafeArea(
top: false,
bottom: false,
child: Form(
autovalidate: autovalidate,
key: _formKey,
child: Scrollbar(
child: SingleChildScrollView(
dragStartBehavior: DragStartBehavior.down,
// padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: new Container(
margin: EdgeInsets.fromLTRB(30, 30, 30, 0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
_buildbusinesslicenseno(),
_buildexpirydate(),
_buildlegalbusinesscheck()
],
),
),
),
),
),
),
),
],
),
),
);
}
#override
Widget build(BuildContext context) {
return new StoreConnector<AppState, BspLicensedSignupViewModel>(
converter: (Store<AppState> store) =>
BspLicensedSignupViewModel.fromStore(store),
onInit: (Store<AppState> store) {
_countryId = store.state.auth.loginUser.user.country.id.toString();
print('_countryId');
print(_countryId);
},
builder: (BuildContext context,
BspLicensedSignupViewModel bspLicensedSignupVm) =>
content(context, bspLicensedSignupVm),
);
}
}
}
The formatter in the onChanged can't format a null date.
So you can add a null check in your DateTimeField's onChanged method.
Like this:
onChanged: (date) {
if (date != null){
_isoDate = DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(date);
}
}