Reputation: 3023
I am trying to add TimePicker in my todo app. But whenever I navigate to the screen where I have added timepicker I get error saying this.
The getter 'hourOfPeriod' was called on null. Receiver: null Tried calling: hourOfPeriod
I have no idea how to fix this or where it is coming from.
These are my code
class _CreateTaskScreenState extends State<CreateTaskScreen> {
final TextEditingController _taskTitleController = TextEditingController();
String taskTitle = '';
bool _taskTitleValidate = false;
DateTime _currentDate = new DateTime.now();
TimeOfDay _currentTime = new TimeOfDay.now();
TimeOfDay selectedTime;
@override
Widget build(BuildContext context) {
/// Time Picker
MaterialLocalizations localizations = MaterialLocalizations.of(context);
String formattedTime = localizations.formatTimeOfDay(selectedTime,
alwaysUse24HourFormat: false);
String timeText = formattedTime;
return Scaffold(
backgroundColor: Color(kPrimaryColor),
appBar: AppBar(
elevation: 0.0,
title: Text('Create a Task'),
),
body: SafeArea(
child: Container(
child: Column(
children: <Widget>[
TimePicker(
icon: Icons.access_time,
selectedTime: '$timeText',
onPress: () async {
selectedTime = await showTimePicker(
context: context,
initialTime: _currentTime,
);
},
),
Anyone, please help me to solve this.
Upvotes: 1
Views: 1337
Reputation: 614
In the first build of the Screen your selectedTime Object is null. Then you want to create a formatted String with it. Which wont work on a null object.
TimeOfDay selectedTime;
String formattedTime = localizations.formatTimeOfDay(selectedTime,
alwaysUse24HourFormat: false);
class _CreateTaskScreenState extends State<CreateTaskScreen> {
final TextEditingController _taskTitleController = TextEditingController();
MaterialLocalizations localizations;
String taskTitle = '';
bool _taskTitleValidate = false;
DateTime _currentDate = new DateTime.now();
TimeOfDay _currentTime = new TimeOfDay.now();
String timeText = 'initText'; //
@override
void didChangeDependencies() {
super.didChangeDependencies();
setState{(){
timeText = localizations.formatTimeOfDay(_currentTime,
alwaysUse24HourFormat: false);
});
}
@override
Widget build(BuildContext context) {
/// Time Picker
localizations = MaterialLocalizations.of(context);
return Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
elevation: 0.0,
title: Text('Create a Task'),
),
body: SafeArea(
child: Container(
child: Column(
children: <Widget>[
TimePicker(
icon: Icons.access_time,
selectedTime: '$timeText',
onPress: () {
showTimePicker(
context: context,
initialTime: _currentTime,
).then(
(TimeOfDay value) => setState(
() {
timeText = localizations.formatTimeOfDay(value,
alwaysUse24HourFormat: false);
},
),
);
},
)
],
),
),
),
);
}
}
Upvotes: 1
Reputation: 879
As said above you're passing slectedTime to formatTimeOfDay function before initialising it first.
Upvotes: 0