Basically when the api pass the date in an invalid format, then it should not crash and the field should display empty
Exception has occurred.
FormatException (FormatException: Invalid date format
NaNNaNNa)
I also try{}catch(e) but the error still shows up
String formattedDate(String date) {
if (date.length >= 8) {
final dateTime = DateTime.tryParse('${date.substring(0, 8)}T${date.substring(8)}');
if (dateTime != null) {
return DateFormat('yyyy-MM-dd').format(dateTime).toString();
}
}
return '';
}
}
void loadTravellerIntoForm(TravellerProfile? traveller) {
String formattedPassportExpiry = '';
if (traveller?.passportExpiry != null &&
traveller?.passportExpiry?.isNotEmpty == true) {
formattedPassportExpiry = DateFormat('dd MMM yyyy').format(
DateTime.parse(traveller?.passportExpiry?.substring(0, 8) ?? ''));
}
passportExpiryDateTextCtrl.text = formattedPassportExpiry;
...}
_TravellerCard(
...
expiryDate: controller.formattedDate(detail.passportExpiry ?? ''),
Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: FormatException: Invalid date format
8 Apr 20. Error thrown while handling a gesture.
at DateTime.parse(dart:core)
at MyTravellersCtrl.loadTravellerIntoForm(my_travellers_ctrl.dart:298)
at _MyTravellersView.build.<fn>.<fn>(my_travellers_page.dart:168)
at _TravellersListView.build.<fn>.<fn>.<fn>(my_travellers_page.dart:752)
at _InkResponseState.handleTap(ink_well.dart:1154)
at GestureRecognizer.invokeCallback(recognizer.dart:275)
at TapGestureRecognizer.handleTapUp(tap.dart:654)
at BaseTapGestureRecognizer._checkUp(tap.dart:311)
at BaseTapGestureRecognizer.acceptGesture(tap.dart:281)
at GestureArenaManager.sweep(arena.dart:167)
at GestureBinding.handleEvent(binding.dart:492)
at GestureBinding.dispatchEvent(binding.dart:468)
at RendererBinding.dispatchEvent(binding.dart:333)
at GestureBinding._handlePointerEventImmediately(binding.dart:413)
at GestureBinding.handlePointerEvent(binding.dart:376)
at GestureBinding._flushPointerEventQueue(binding.dart:323)
at GestureBinding._handlePointerDataPacket(binding.dart:292)```
3
Answers
try this and let me know, if the issue is still there.
The error is from the line below:
Using null-aware operator (
?.
) might seems like it will prevent exceptions, but in fact, iftraveller
andpassportExpiry
are both not null, the value is evaluated to theparse
method, and if the format happens to be invalid, it will throwFormatException
.You might want to change it to this:
The error says that
traveller?.passportExpiry?.substring(0, 8)
actually is8 Apr 20
. Which is not an accepted format forDateTime.parse(
. For that you would need to doDateFormat('dd MMM yyyy').parse(
instead. But the thing is this is already the format that you would like to have so it seems the entire conversion is unnecessary