Flutter asset loading error: No file or variants found for asset

No file or variants found for asset is an error that prevents running the Flutter app when the assets path are not defined properly. The following are some common causes:

  • The path defined in pubspec.yaml does not match with the actual folder path for the asset folder you created in the project.
  • The indentation is not correct for the assets path defined in pubspec.yaml
  • Mistakenly think the assets keyword in pubspec directly maps to the assets folder that you created.
  • As an example, here is a project root files and folders structure. The assets folder and it’s sub-folder images and json are manually created after project initialization. The assets folder is named with assets, but it can be any other names, as well as the sub folders inside it, they can be any other names.

    ┬
    └ project_name
      ┬
      ├ android
      ├ assets     - This folder its sub-folders does not come from project initialization.
        ┬
        └ images/
        └ json/          
      ├ build        
      ├ ios          
      ├ lib          
        ┬
        └ src        
        └ main.dart  
                       
                        
                       
      ├ test         
      └ pubspec.yaml 
    

    In order for Flutter to recognize the asset folder, its sub folders, image or json files. The path to those folders that you created has to be defined in the pubspec.yaml file.

  • Make sure there are exactly 2 spaces between the left most of the file and assets:
  • Make sure there are exactly 4 spaces between the left most of the file and - assets/images/
  • Make sure there are exactly 4 spaces between the left most of the file and - assets/json/
  • It is assets/images/ and assets/json/ because the folder that you created at the project root is assets with sub-folders images and json
  • The assets keyword does not automatically maps to the assets folder that you created. If you named the folder assets, then assets has to be specified in the paths under the keyword assets:
  • flutter
      assets:
        - assets/images/
        - assets/json/
    

    If there is a json file data.json in assets/json/data.json, it can be loaded like this. The file path in rootBundle.loadString starts from the project root folder.

    import 'package:flutter/services.dart';
    
    final String response = await rootBundle.loadString('assets/json/data.json');
    final data = await json.decode(response);
    print(data);
    

    Search within Codexpedia

    Custom Search

    Search the entire web

    Custom Search