Flutter中DateTime.parse触发FormatException(无效日期格式)问题排查求助
Let's break down why this exception pops up occasionally and how to fix it cleanly:
Root Cause
The issue hits when the app runs for the first time (or the storage key is missing/corrupted). Your code defaults lastNoBikeAlertShowUp to an empty string "" if the storage value doesn't exist, and DateTime.parse("") can't turn an empty string into a valid DateTime object—this directly triggers the FormatException.
There's also a small risk the stored date string could get corrupted over time, so we need to handle invalid formats gracefully too.
Solution
We'll make two key improvements:
- Swap
DateTime.parse()forDateTime.tryParse(): This method returnsnullinstead of throwing an exception when parsing fails, letting us handle invalid cases safely. - Add logic to treat empty/invalid stored values as "never showed the alert before".
Modified Code
Here's the updated else block of your function with the fixes applied:
} else { print("favoriteBike null in initListOfUsageValues"); // Check if the no-bike alert has been displayed before final storage = new FlutterSecureStorage(); String lastNoBikeAlertShowUp = await storage.read(key: "last_no-bike-alert_show-up") ?? ""; // Safely parse the stored date (returns null if invalid/empty) DateTime? lastNoBikeAlertShowUpDateTime = DateTime.tryParse(lastNoBikeAlertShowUp); var now = DateTime.now(); // Determine if we should show the alert bool shouldShowAlert = false; if (lastNoBikeAlertShowUpDateTime == null) { // No valid date stored = first run or corrupted storage → show alert shouldShowAlert = true; } else { int minutesSinceLastAlert = now.difference(lastNoBikeAlertShowUpDateTime).inMinutes; shouldShowAlert = minutesSinceLastAlert > 60; } if (shouldShowAlert) { await storage.write( key: "last_no-bike-alert_show-up", value: now.toString()); showDialog( context: context, builder: (BuildContext context) { return noBikeYetAlertDialog(context); }); } }
Key Changes Explained
DateTime.tryParse(): Eliminates exceptions by returningnullfor invalid inputs like empty strings.- Null check handling: If parsing fails, we immediately decide to show the alert (since it's either the first run or storage is corrupted).
- Cleaner conditional logic: Separated the alert decision into a boolean variable for better readability and maintainability.
This fixes the occasional FormatException and makes your code more resilient to unexpected storage states.
内容的提问来源于stack exchange,提问作者weaked

