Home > front end >  adding and reading a JSON asset in Flutter Web app
adding and reading a JSON asset in Flutter Web app

Time:09-27

Got a problem reading an asset in Flutter web app. I've declared it in pubspec.yaml

enter image description here

But when I'm trying to load it with await rootBundle.loadString('test/sample_text.json'); I always get the same error Error while trying to load an asset: Failed to load asset at "assets/test/sample_text.json" Never had such issue when developing for mobile

CodePudding user response:

Assets in the web are placed under another assets/ directory, which results in the path being assets/assets/....

Create a simple function e.g. in lib/utils.dart:

import 'package:flutter/foundation.dart';

String path(str) {
  return (kIsWeb) ? 'assets/$str' : str;
}

Wrap any path strings with this function, for example

AssetImage(path('test/sample_text.json')).

CodePudding user response:

the correct way to do this is packages/$your_package/assets/test/sample_text.json

  • Related