Flutter开发模式正常,打包APK后无法加载Assets中JSON文件求助
Hey there! I totally get how frustrating this is—when something works perfectly in debug but breaks in the released build, it’s usually a small oversight that’s easy to fix. Let’s walk through the most common issues and how to resolve them:
1. Double-Check Your pubspec.yaml Assets Configuration
This is the #1 culprit for asset loading issues in release builds. Make sure your assets are properly declared under the flutter section with correct indentation (YAML is strict about this!).
Correct example:
flutter: uses-material-design: true # Ensure assets are indented under the flutter node assets: - assets/your_data.json # Exact path to your JSON file # If loading all files in a folder, add a trailing slash: # - assets/data_folder/
After updating pubspec.yaml, run flutter clean followed by flutter build apk—build cache can sometimes hold onto old, incorrect configurations.
2. Verify Path Case Sensitivity
Debug mode on Windows/macOS is case-insensitive, but Android (built on Linux) treats file paths as strictly case-sensitive. If your code references Assets/My_Data.json but the actual file is named assets/my_data.json, it’ll work in debug but fail in the APK.
Fix: Ensure the path in your rootBundle.loadString() call exactly matches the file’s actual path (including uppercase/lowercase letters).
3. Add Error Handling to Debug the Root Cause
Without error logging, you won’t know exactly why the asset isn’t loading. Wrap your asset loading code in a try-catch block to capture errors, then check the Android logcat for details.
Example code:
import 'package:flutter/services.dart' show rootBundle; Future<String> loadJsonAsset() async { try { return await rootBundle.loadString('assets/your_data.json'); } catch (e) { print('Failed to load JSON: $e'); // This will show up in logcat return ''; } }
To view logcat output for your release APK, connect your phone to your computer and run:
adb logcat -s Flutter
Look for lines like Unable to load asset: assets/your_data.json—this will point you directly to the problem.
4. Do a Clean Build
Old build artifacts can sometimes cause assets to be excluded from the APK. Run these commands to create a fresh build:
flutter clean flutter build apk --release
This ensures all assets are properly bundled into the new APK.
5. Check for ProGuard/R8 Obfuscation Issues (Rare but Possible)
If you’ve enabled ProGuard or R8 obfuscation in your Android project, it might accidentally strip or modify your JSON assets. To prevent this, add a rule to your android/app/proguard-rules.pro file:
# Keep all assets from being modified or removed -keepresources assets/**
Then rebuild your APK.
Start with the first two steps—they’re the most common fixes. If those don’t work, use the error handling to get more details, and we can narrow it down further!
内容的提问来源于stack exchange,提问作者Akash khan

