Search code examples
dartdart-html

Using Dart for HTML5 app, but want to load a file from the server-side


I'm new to Dart, and trying to create my first Dart web game. Sorry if I missed an answered question related to this. I did search, but wasn't having much luck.

To load a level, I would like to be able to read in a text file with the level data, then process that and use it to build the level. Unfortunately, I am running into the issue where dart:io and dart:html can not both be loaded if you want to use the File() object. From what I can tell, dart:html's File() object is client-side, so that would not be able to open the text-file I will have on the server.

Is there another way to read in a text file from the server? If not, do I need to set up a database just to store the game data, or is there a better option I'm not thinking about here?

In case it helps, the game data I'm working with currently is just a text file that gives a map of what the level will look like. For example:

~~~~Z~~~~

P

GGGGLLGGG

Each of those characters would denote a type of block to be placed in the level. It's not the best way to store levels, but it is pretty easy to create and easy to read in and process.

Thanks so much for the help!


Solution

  • If the file you are loading is a sibling of the index.html your game is loaded from, then you can just make an HTTP request to fetch the file.

    To download web/level1.json you can use

    Future<String> getGameData(String name) {
      var response = await HttpRequest.getString('${name}.json');
      print(response);
      return response;
    }
    
    otherMethod() async {
      var data = await getGameData('level1');
    }
    

    See also https://api.dartlang.org/stable/1.24.3/dart-html/HttpRequest-class.html