menefrego
menefrego

Reputation: 115

adding and reading a JSON asset in Flutter Web app

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

Upvotes: 0

Views: 837

Answers (2)

Răzvan Puiu
Răzvan Puiu

Reputation: 731

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('assets/test/sample_text.json')).

Upvotes: 1

menefrego
menefrego

Reputation: 115

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

Upvotes: 0

Related Questions