date picker is not showing months correctly - flutter - flutter

am taking date of birth from users while registering, users click on the form field so date picker shows and they choose their date of birth, the problem is for example user chooses "15-October-1996", the months always show as "00" like this "15-00-1996" here is the "DateTimeField()" code:
final birthDateField = DateTimeField(
controller: dateController,
format: DateFormat("dd-mm-yyyy"),
onShowPicker: (context, currentValue) async {
final date = await showDatePicker(
context: context,
initialDate: currentValue ?? DateTime.now(),
firstDate: DateTime(1920),
lastDate: DateTime(2030));
return date;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
labelText: 'تاريخ الميلاد',
prefixIcon: Icon(Icons.calendar_month),
),
);
and i rendered the fields inside a Scaffold widget as follows:
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.purple,
),
onPressed: () {
Navigator.of(context).pop();
},
),
),
body: Center(
//Use the SingleChildScrollView as a wrapper to ensure scrolling in case scorrling is needed.
child: SingleChildScrollView(
//wrap the elements with Container to provide flexibility in designing the elements.
child: Container(
color: Colors.white,
//use the form as a container of the input fields as it is a login form.
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Form(
//give the form wrapper the key value to tell flutter that this is the form design for your form functions.
key: _formKey,
//use the column to show the elements in vertical array.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
//Use children property inside the column to specify list of widgets
children: [
birthDateField,
SizedBox(
height: 20,
),
signUpButton,
]),
),
),
),
),
),
);
am using a controller to update values and send to database, i also imported all the necessary packages, so am not sure what am missing i would be thankful for any help.

Try changing the dataformat with format: DateFormat("dd-MM-yyyy"),

change your formatter to "dd-MM-yyyy":
final birthDateField = DateTimeField(
controller: dateController,
format: DateFormat("dd-MM-yyyy"), //<- change this
onShowPicker: (context, currentValue) async {
final date = await showDatePicker(
context: context,
initialDate: currentValue ?? DateTime.now(),
firstDate: DateTime(1920),
lastDate: DateTime(2030));
return date;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
labelText: 'تاريخ الميلاد',
prefixIcon: Icon(Icons.calendar_month),
),
);
```

Related

How to remove default cross icon from datetimefield in flutter?

Center(
child: Container(
width: MediaQuery.of(context).size.width / 2.5,
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent,width: 1),
color: colorPrimary,
borderRadius: radius(10),
),
padding: EdgeInsets.symmetric(horizontal: 5.w),
child: Row(
mainAxisSize: MainAxisSize.max,
children: [
const Icon(Icons.calendar_month,size: 20),
Expanded(
child: Theme(
data: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: InputBorder.none,
)
),
child: DateTimeField(
// readOnly: _isDateTimeReadonly,
controller: _dobController,
cursorColor: white,
format: format,
onShowPicker: (context, currentValue) {
if (_dobController.text.isEmpty) _selectedDate = "";
// else if (!_isDateTimeReadonly)
return showDatePicker(
context: context,
initialDate: currentValue ?? DateTime.now(),
// initialDate: _selectedDate!.isNotEmpty ? DateTime.parse(_selectedDate!) : DateTime.now(),
firstDate: DateTime(1900),
lastDate: DateTime.now(),
// lastDate: DateTime.now().subtract(Duration(days: 6570)),
).then((res) {
if (res != null) {
_selectedDate = res.toLocal().toString().split(' ')[0];
_dobController.text = _selectedDate!;
isDateSelected = true;
_affiliateReward.currentState!.refreshData();
print('Response Date : ${res}');
print('isDateSelected : ${isDateSelected}');
}
return res;
});
},
),
),
),
const Icon(Icons.calendar_month,size: 20),
],
),
),
),
So, above code is for datetimefield. I want to remove default cross icon. How do I remove it?
In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available.
Try the suffixIcon and suffix property , and pass empty Container.
DateTimeFormField(
decoration: const InputDecoration(
suffixIcon: Container(),
// or
suffix: Container(),
),
// your other stuff
),

[Flutter]How to import image from gallery dynamically

I am a new flutter learner and trying to create my first app. My problem is...
(1). I use a method to build a place(widget) for image which will come from gallery or camera.
void _showPicker(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.photo_library),
title: new Text('Gallery'),
onTap: () {
_imgFromGallery();
Navigator.of(context).pop();
}),
new ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () {
_imgFromCamera();
Navigator.of(context).pop();
},
),
],
),
),
);
});
}
(2). I created a method to import image by using image_picker package.
Future _imgFromGallery() async {
final pickedImage =
await _picker.getImage(source: ImageSource.gallery, imageQuality: 50);
setState(() {
if (pickedImage != null) {
this._image = new File(pickedImage.path);
}
});
}
(3). I create a button which if pressed, will call method (1) and medthod (1) contained medthod (2).
(4). When I added the first image, everything fine but, when I add the second image, the first image also changed to the second
image
So, could you please help me for figure out of this problem?
Sorry that I didn't share the code that call _showPicker (function for displayed image) here is the code...please focus at GestureDetector(...),
_createListStepRow(String item, int index) {
return Column(children: [
Container(
margin: EdgeInsets.only(top: 3),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: new BorderRadius.circular(15),
border: Border.all(color: Colors.black)),
child: Column(children: [
Row(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
Container(
width: 1175.0.w,
child: TextField(
autofocus: this.autoFocus,
cursorColor: Colors.black,
decoration: InputDecoration(
prefixIcon: Icon(
Icons.restaurant_outlined,
color: Constants.primaryColor,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(color: Colors.white, width: 1.5),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(color: Colors.white, width: 0),
),
contentPadding: EdgeInsets.symmetric(vertical: 8),
hintText: item,
floatingLabelBehavior: FloatingLabelBehavior.never,
)),
),
IconButton(
icon: Icon(Icons.delete),
onPressed: () {
setState(() {
_itemsStep.removeAt(index);
});
},
),
]),
GestureDetector(
onTap: () async {
_showPicker(context);
},
child: Container(
padding: EdgeInsets.all(8),
// height: 800.0.h,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.grey[200],
// image: DecorationImage(
// image: AssetImage('assets/images/food1.jpg'),
// fit: BoxFit.fill,
// ),
shape: BoxShape.rectangle,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
new Column(children: [
Container(
// height: 200.0.h,r
child: _image == null
? _nullImage
: Image.file(_image, fit: BoxFit.contain),
),
// Text(
// 'Click to Add Step Image',
// style: GoogleFonts.poppins(fontSize: 14),
// ),
]),
]),
),
),
SizedBox(height: 60.0.h),
]),
),
SizedBox(height: 30.0.h),
]);
}
First off, you're not storing the images. You're basically choosing the latest one. Lets fix that. Find where you've declared var _image; and change that to final List<File> _images;.
Next, change the Column in the GestureDetector in _showPicker to this:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
new ListView.builder(
itemBuilder: (context, index) {
return Container(
// height: 200.0.h,r
child: _images[index] == null
? _nullImage
: Image.file(_images[index], fit: BoxFit.contain),
);
},
itemCount: _images.length,
// Text(
// 'Click to Add Step Image',
// style: GoogleFonts.poppins(fontSize: 14),
// ),
)
],
),
If the code you gave was working as you said before, this should probably work.

Flutter create new instance of class on button tap and update values

I am creating a feature for users to be able to add occasions (title and date) to a list in Flutter. I have set up the features but i'm struggling to understand how to firstly, create a new instance of my DateToRemember class when my "add button" is pressed and then, when a title text value is entered, and a date selected from my datepicker, update that instance with those values. Then users will be able to click a submit button and their list updated.
Here is my date to remember model:
class DateToRemember {
String title;
DateTime date;
DateToRemember(this.title, this.date);
}
And the datestoremember page code:
class DatesToRemember extends StatefulWidget {
#override
_DatesToRememberState createState() => _DatesToRememberState();
}
class _DatesToRememberState extends State<DatesToRemember> {
TextEditingController _titleController = new TextEditingController();
DateTime startDate = DateTime.now();
DateTime pickedDate = DateTime.now();
DateFormat formatter = DateFormat('dd/MM/yyyy');
_DatesToRememberState();
Future displayDatePicker(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: startDate,
firstDate: startDate,
lastDate: DateTime(DateTime.now().year + 100));
if (picked != null)
setState(() {
pickedDate = picked;
print(DateFormat('dd/MM/yyyy').format(pickedDate).toString());
});
}
final List<DateToRemember> occasions = [
DateToRemember("Occasion 1", DateTime.now()),
DateToRemember("Occasion 2", DateTime.now()),
DateToRemember("Occasion 3", DateTime.now()),
];
String input;
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
leading: GestureDetector(
onTap: () => Navigator.pop(context),
child: Icon(Icons.arrow_back)),
title: Text('Dates to Remember'),
),
backgroundColor: Colors.white,
body: Center(
child: Column(children: [
SizedBox(
height: 10.0,
),
Container(
width: MediaQuery.of(context).size.width * 0.8,
child: Text(
"It can be difficult to ",
style: TextStyle(fontFamily: FontNameDefault),
),
),
SizedBox(
height: 50.0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Align(
alignment: Alignment.centerRight,
child: FloatingActionButton(
backgroundColor: kPrimaryColor,
child: Icon(Icons.add),
onPressed: () {
// CREATE NEW INSTANCE OF DATETOREMEMBER CLASS
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Add occasion'),
content: Container(
height: 150.0,
child: Column(
children: [
TextField(
decoration: InputDecoration(
hintText: 'Occasion Title'),
//UPDATE TITLE IN CLASS WITH INPUT
//
),
TextField(
decoration: InputDecoration(
hintText: 'Pick Date'),
onTap: () async {
await displayDatePicker(context);
//SELECT DATE AND UPDATE INSTANCE OF CLASS
},
),
FlatButton(
child: Text('Submit'),
onPressed: () {
//Navigator.of(context).pop();
},
),
],
),
),
);
});
}),
),
),
Container(
height: MediaQuery.of(context).size.height * 0.6,
width: MediaQuery.of(context).size.width * 0.9,
decoration:
BoxDecoration(border: Border.all(color: Colors.black26)),
child: occasions.isEmpty
? Center(
child: Text(
'Add an occasion',
style: TextStyle(color: Colors.black),
))
: ListView.builder(
itemCount: occasions.length,
itemBuilder: (BuildContext context, int index) {
return Dismissible(
direction: DismissDirection.endToStart,
onDismissed: (direction) {
occasions.removeAt(index);
Scaffold.of(context).showSnackBar(new SnackBar(
content: Text('Occasion Removed'),
duration: Duration(seconds: 5),
));
},
key: UniqueKey(),
child: Card(
elevation: 8.0,
margin: EdgeInsets.all(8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
child: ListTile(
title: Text(occasions[index].title),
subtitle: Text(DateFormat('dd/MM/yyyy')
.format(occasions[index].date)
.toString()),
trailing: IconButton(
icon: Icon(
Icons.delete,
color: Colors.red,
),
onPressed: () {
setState(() {
occasions.removeAt(index);
Scaffold.of(context)
.showSnackBar(new SnackBar(
content: Text('Occasion Removed'),
duration: Duration(seconds: 5),
));
});
},
),
),
),
);
}),
)
]),
));
}
}
I'm still a flutter/dart novice so not entirely sure if what i'm asking is the best way to achieve what I want, so open to new ideas also. Thanks.

Flutter/Dart how to pick a date and populate text field with selection

I am trying to let users add dates to a list in my app and I have managed to create my text field as well as the date selector. I am struggling to set the value of the selected date to a variable and populate the text field when a user picks one. I have tried accessing the _date value from _selectDate but still nothing populates my TextField.
Here is my code:
class DatesToRemember extends StatefulWidget {
#override
_DatesToRememberState createState() => _DatesToRememberState();
}
class _DatesToRememberState extends State<DatesToRemember> {
DateTime selectedDate = DateTime.now();
TextEditingController _date = new TextEditingController();
Future<Null> _selectDate(BuildContext context) async {
DateFormat formatter =
DateFormat('dd/MM/yyyy'); //specifies day/month/year format
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1901, 1),
builder: (BuildContext context, Widget child) {
return Theme(
data: ThemeData.light().copyWith(
colorScheme: ColorScheme.light(
primary: kPrimaryColor,
onPrimary: Colors.black,
),
buttonTheme: ButtonThemeData(
colorScheme: Theme.of(context)
.colorScheme
.copyWith(primary: Colors.black),
),
),
child: child,
);
},
lastDate: DateTime(2100));
if (picked != null && picked != selectedDate)
setState(() {
selectedDate = picked;
_date.value = TextEditingValue(
text: formatter.format(
picked));//Use formatter to format selected date and assign to text field
});
return _date;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: GestureDetector(
onTap: () => Navigator.pop(context),
child: Icon(Icons.arrow_back)),
title: Text('Dates to Remember'),
),
backgroundColor: Colors.white,
body: Center(
child: Column(children: [
SizedBox(
height: 10.0,
),
Container(
width: MediaQuery.of(context).size.width * 0.8,
child: Text(
"It can be difficult to ",
style: TextStyle(fontFamily: FontNameDefault),
),
),
SizedBox(
height: 50.0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Align(
alignment: Alignment.centerRight,
child: FloatingActionButton(
backgroundColor: kPrimaryColor,
child: Icon(Icons.add),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Add occasion'),
content: Container(
height: 150.0,
child: Column(
children: [
TextField(
onChanged: (String value) {
input = value;
},
decoration: InputDecoration(
hintText: 'Occasion Title'
),
),
TextField(
decoration: InputDecoration(
hintText: 'Pick Date'
),
onTap: () => _selectDate(context),
),
FlatButton(
child: Text('Add'),
onPressed: () {
setState(() {
occasions.add(input);
});
Navigator.of(context).pop();
},
),
],
),
),
);
});
}),
),
),
Container(
height: MediaQuery.of(context).size.height * 0.6,
width: MediaQuery.of(context).size.width * 0.9,
decoration: BoxDecoration(
border: Border.all(color: Colors.black26)
),
child:
occasions.isEmpty? Center(child: Text('Add an occasion', style: TextStyle(
color: Colors.black
),)) : ListView.builder(
itemCount: occasions.length,
itemBuilder: (BuildContext context, int index) {
return
Dismissible(
direction: DismissDirection.endToStart,
onDismissed: (direction) {
occasions.removeAt(index);
Scaffold.of(context).showSnackBar(new SnackBar(
content: Text('Occasion Removed'),
duration: Duration(seconds: 5),
));
},
key: UniqueKey(),
child: Card(
elevation: 8.0,
margin: EdgeInsets.all(8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
child: ListTile(
title: Text(occasions[index]),
trailing: IconButton(
icon: Icon(
Icons.delete,
color: Colors.red,
),
onPressed: () {
setState(() {
occasions.removeAt(index);
Scaffold.of(context).showSnackBar(new SnackBar(
content: Text('Occasion Removed'),
duration: Duration(seconds: 5),
));
});
},
),
),
),
);
}),
)
]),
));
}
}
Can someone help? Thanks
Try my code below:
DateTime valueDate = DateTime.now();
Row(
children: <Widget>[
Container(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 0),
child: Text("${valueDate.toLocal()}".split(' ')[0]),
),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Theme.of(context).accentColor,
width: 2.5,
),
)),
width: 270,
),
RaisedButton(
child: Icon(Icons.date_range),
onPressed: () => _selectDate(context),
)
],
);
The function :
Future<Null> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(context: context, initialDate: valueDate, firstDate: DateTime(2015, 8), lastDate: DateTime(2101));
if (picked != null && picked != valueDate)
setState(() {
valueDate = picked;
});
}

How can I make the leading flutter date icon clickable and selectable widget?

Below is my flutter code and I would like to make the leading calendar icon launch a calendar widget for date selection in the last textfield just before the raised button as marked below in code.
** widget starts inside stateful class**
#override
Widget build(BuildContext context) {
var db = DBHelper();
return Scaffold(
appBar: AppBar(
title: Text('Add'),
),
body: Container(
padding: EdgeInsets.only(top: 30, left: 50, right: 50),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
TextField(
keyboardType: TextInputType.text,
decoration: InputDecoration(
icon: Icon(Icons.bookmark), hintText: 'nickname'),
controller: nameController,
),
const SizedBox(height: 15),
TextField(
decoration: InputDecoration(
icon: Icon(Icons.date_range), hintText: 'date created'),
controller: otherController,
),
const SizedBox(height: 50),
RaisedButton(
onPressed: () {
db.saveAssets(Asset(
name: nameController.text,
other: otherController.text));
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyAssetsList()),
);
},
padding: EdgeInsets.only(left: 18, right: 18),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
textColor: Colors.white,
color: Colors.lightGreen,
splashColor: Colors.lightGreenAccent,
child: const Text(
'Save',
style: TextStyle(fontSize: 20),
),
),
],
),
),
),
);
}
}
One more solution.
If you want only the calendar icon to be tapable (while still having similar design to the one you've provided):
Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.date_range),
padding: EdgeInsets.zero,
onPressed: () {
print('Yay!');
},
),
Expanded(
child: TextField(
decoration: InputDecoration(
hintText: 'Date Created',
),
readOnly: true, // Or wrap the input with AbsorbPointer if you do not want the field to get highlighted by taping on it
),
),
],
)
If you want to let the user input the date by typing - just remove the readOnly attribute from the input.