read json file flutter

To read a JSON file in Flutter, you can follow these steps:

  1. Import the dart:convert package to handle JSON data.
  2. Use the rootBundle object from the flutter/services.dart package to access the file.
  3. Use the rootBundle.loadString() method to load the JSON file as a string.
  4. Parse the JSON string using the jsonDecode() function from the dart: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
  } 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:

    - assets/data.json

That's it! You can now use the readJsonFile() function to read the JSON file in your Flutter app.