FlutterError: Unable to load asset

后端 未结 22 3360
死守一世寂寞
死守一世寂寞 2020-11-30 10:31

This is the folder structure of my app

.idea
.vscode
android
build
fonts
 Oxygen-Bold.tff
 Oxygen-Light.tff
 Oxygen-Regular.tff
images
 pizza0.png
 pizza1.pn         


        
22条回答
  •  情歌与酒
    2020-11-30 11:26

    I ran into this issue and very nearly gave up on Flutter until I stumbled upon the cause. In my case what I was doing was along the following lines

    static Future resourceText(String resName) async
    {
     try
     { 
      ZLibCodec zlc = new ZLibCodec(gzip:false,raw:true,level:9);
      var data= await rootBundle.load('assets/path/to/$resName');
      String result = new 
      String.fromCharCodes(zlc.decode(puzzleData.buffer.asUint8List()));
      return puzzle;
     } catch(e)
     {
      debugPrint('Resource Error $resName $e');
      return ''; 
     } 
    }
    
    static Future fallBackText(String textName) async
    {
     if (testCondtion) return 'Some Required Text';
     else return resourceText('default');
    } 
    

    where Some Required Text was a text string sent back if the testCondition was being met. Failing that I was trying to pick up default text from the app resources and send that back instead. My mistake was in the line return resourceText('default');. After changing it to read return await resourceText('default') things worked just as expected.

    This issue arises from the fact that rootBundle.load operates asynchronously. In order to return its results correctly we need to await their availability which I had failed to do. It strikes me as slightly surprising that neither the Flutter VSCode plugin nor the Flutter build process flag up this as an error. While there may well be other reasons why rootBundle.load fails this answer will, hopefully, help others who are running into mysterious asset load failures in Flutter.

提交回复
热议问题