read json file flutter
To read a JSON file in Flutter, you can follow these steps:
- Import the
dart:convert
package to handle JSON data. - Use the
rootBundle
object from theflutter/services.dart
package to access the file. - Use the
rootBundle.loadString()
method to load the JSON file as a string. - Parse the JSON string using the
jsonDecode()
function from thedart:convert
package.
Here's an example code snippet that demonstrates how to read a JSON file in Flutter:
import 'dart:convert';
import 'package:flutter/services.dart';
Future<void> readJsonFile() async {
try {
// Load the JSON file as a string
String jsonString = await rootBundle.loadString('assets/data.json');
// Parse the JSON string
var jsonData = jsonDecode(jsonString);
// Access the data from the JSON object
// Example: print the value of a key
print(jsonData['key']);
} catch (e) {
print('Error reading JSON file: $e');
}
}
In this example, the JSON file is assumed to be located in the assets
folder of your Flutter project. Make sure to update the file path accordingly.
Remember to add the JSON file to your project's pubspec.yaml
file under the assets
section:
flutter:
assets:
- assets/data.json
That's it! You can now use the readJsonFile()
function to read the JSON file in your Flutter app.