You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中DateTime.parse触发FormatException(无效日期格式)问题排查求助

Fixing FormatException: Invalid date format in DateTime.parse()

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() for DateTime.tryParse(): This method returns null instead 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 returning null for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:47:43