flutter data_error ai_generated true

FormatException:读取 SharedPreferences 时出现无效的十进制数字(字符 1)

FormatException: Invalid radix-10 number (at character 1) while reading SharedPreferences

ID: flutter/shared-preferences-corruption

其他格式: JSON · Markdown 中文 · English
78%修复率
83%置信度
1证据数
2024-04-05首次发现

版本兼容性

版本状态引入弃用备注
Flutter 3.22 active
Dart 3.4 active
Android 13 active
iOS 16 active

根因分析

SharedPreferences(或 NSUserDefaults)中存储的值应为整数,但已损坏或保存为非数字字符串,通常是由于版本不匹配或手动编辑所致。

English

A value stored in SharedPreferences (or NSUserDefaults) was expected to be an integer but was corrupted or saved as a non-numeric string, often due to version mismatches or manual editing.

generic

官方文档

https://api.flutter.dev/flutter/package-shared_preferences-shared_preferences/SharedPreferences-class.html

解决方案

  1. Use a migration function that reads the corrupted value as a string, attempts to parse it, and if it fails, removes the key and sets a default. Example: `final raw = prefs.getString('counter'); int? value; try { value = int.parse(raw!); } catch (e) { await prefs.remove('counter'); value = 0; }`
  2. Implement a versioned SharedPreferences wrapper that validates data types on read and repairs corrupted entries automatically.
  3. For critical data, migrate to a more robust storage solution like Hive or Isar that includes type safety and corruption detection.

无效尝试

常见但无效的做法:

  1. 40% 失败

    This deletes all user preferences, causing loss of user settings and potentially breaking app functionality; it's a nuclear option that should only be used as a last resort.

  2. 70% 失败

    The corruption remains in storage and will cause the same error on every app restart; the default value may not match user expectations.

  3. 95% 失败

    Not feasible for production apps; root access is rare and editing XML can cause further corruption or crash the app.