Using DART language to read a JSON file stored locally on the client side, eliminating the need for a server

Having some trouble reading data from a JSON file with the following code:

void fetchData(Event e){  
     var path='json/data.json';
     var request= new HttpRequest();
     request
       ..open('GET', path)
       ..onLoadEnd.listen((e)=>handleResponse(request))
       ..send('');
}

Everything works fine when running the app as http:// .../ index.html, but encountered an error when trying to open it as file:///.../index.html

Exception: NetworkError: Failed to load 'file:///D:/SampleApp/web/json/data.json'. main.dart:53fetchData main.dart:53<anonymous closure>

I'm wondering if there is another method besides using httpRequest to read a JSON file on the client side!

As far as I can tell, I have 3 options, two of which involve using HttPRequest:

  1. Saving the file on the server and fetching it remotely => can use HttpRequesit
  2. Saving the file on the server and loading it from the client => can use HttpRequesit
  3. Saving the file directly on the client and reading it there => CAN NOT use HTTPRequest

I am particularly interested in pursuing the third option, similar to creating an offline Android App using webview or an offline Chrome packaged app. In this case, I do not want to rely on a server at all. Thank you

Thanks again

Answer №1

If you only require the data in the json file, you can simply embed that data within your .dart files (such as a Map variable/constant).

Map config = {
   "displayName": "My Display Name",
     "anotherProperty": 42,
     "complexProperty": {
         "value_1": "actual value",
         "value_2": "another value"
     }
   };

If you need the actual json content, you can store it as a String. For instance:

const configJson = '''
   { "displayName": "My Display Name",
     "anotherProperty": 42,
     "complexProperty": {
         "value_1": "actual value",
         "value_2": "another value"
     }
   }
''';

The json data could be placed in a separate .dart file, which may then be included within the same library using part of ..., or imported using

import 'package:mypackage/json.dart';
.

If you are seeking a solution where changes persist, offline storage will be required. This could be achieved with web storage if operating within a browser environment. You can follow the method above to define initial configuration data, save it in web storage, and subsequently read and update it from there.

[Previous response below, prior to original question editing.]

Apologies for the confusion earlier when mentioning "client side" instead of "server side". My error.

If by "client side", you mean running in a browser and attempting to access a json file on the server, then HTTP requests are indeed necessary. This is the sole method to read any file on the server, including json ones. (Alternatively, establishing a WebSocket connection to stream the content could be considered, although it might not align with what you're seeking.)

[Original solution provided before acknowledging the mistake between server and client environments:]

You can attempt:

// NOTE: THIS APPROACH IS NOT SUITABLE FOR BROWSER ENVIRONMENTS (i.e., CLIENT SIDE)
import 'dart:io';
import 'dart:convert';


// ...

new File('json/config.json')
    .readAsString()
    .then((fileContents) => json.decode(fileContents))
    .then((jsonData) {
        // perform actions based on the received data
    });

Answer №2

This particular example functions perfectly within the chrome development editor for a dart web application. Utilizing HttpRequest.getString is effective when working with filenames and paths.

For more information on handling json web services, check out Chris' informative article at

import 'dart:html';
import 'dart:convert';

void main() {
  HttpRequest.getString('json/config.json').then((myjson) {
    Map data = JSON.decode(myjson); 
    var version = data["version"];
    var element = new DivElement();
    element.text = "version = $version";
    document.body.children.add(element);
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

What is the process of using an if statement in jQuery to verify the existence of a property in a JSON file?

I am working on a task to incorporate an if statement that checks for the existence of a specific property in a JSON file. If the property exists, I need to display its value within HTML tags <div class='titleHolder'> and "<div class=&ap ...

fullcalendar adjusting color while being moved

Currently, I have implemented a fullcalendar feature that displays entries for multiple users with different colored calendars. However, there seems to be an issue when dragging an entry to another date - the color reverts back to default. Below is an exa ...

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

CSS background image referencing in React to the public folder's path

I am currently working on a project using Create-React-App and I am trying to set a background image for my header section. Here is how I'm attempting to do it: background-image: url('~/Screenshot_11.png'); However, I encountered an error w ...

Is it acceptable to replicate another individual's WordPress theme and website design in order to create my own WordPress website that looks identical to theirs?

It may sound shady, but a friend of mine boasts about the security of his WordPress website, claiming it's impossible to copy someone else's layout or theme. However, my limited experience in web development tells me otherwise. I believe it is po ...

Trouble displaying data in Jquery JSON

I've been on the hunt for hours, trying to pinpoint where the issue lies within my code. Despite scouring different resources and sites, I can't seem to figure it out. Whenever I click "Get JSON Data," nothing seems to display below. Can someone ...

What is the best way to create a unique shadow effect for a container in Flutter?

I am facing a challenge with my screen layout that uses GridView.builder with crossAxisCount: 3. In the itemBuilder, I am returning a Container with shadows on the left, right, and bottom, but so far, I have not been able to achieve the desired outcome. H ...

Retrieve jQuery CSS styles from a JSON database

I've been attempting to pass CSS attributes into a jQuery method using data stored in a JSON database. However, it doesn't seem to be functioning as expected. I suspect that directly inputting the path to the JSON variable may not be the correct ...

What is the best way to add custom styles to an Ext JS 'tabpanel' xtype using the 'style

Is there a way to change the style of a Ext.tab.Panel element using inline CSS structure like how it's done for a xtype: button element? { xtype: "button", itemId: "imageUploadButton1", text: "Uploader", style: { background : ' ...

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...