首页 > 解决方案 > Flutter background image "Unable to decode bytes as UTF-8"

问题描述

I am working on a flutter app, and want to use a background image. Here is my code so far which I got from the following stack overflow page: Flutter SDK Set Background image

import 'package:flutter/material.dart';
import 'backgroundpic.jpeg';

void main() {
  runApp(MyApp());
}

class BaseLayout extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("backgroundpic.jpeg"),
            fit: BoxFit.cover,
          ),
        ),
        child: null /* add child content here */,
      ),
    );
  }
}

The issue is, when I run this app, I get a huge list of errors revolving around "unable to decode bytes as UTF-8."

Here is the list of errors:

lib/backgroundpic.jpeg:6:300: Error: Unable to decode bytes as UTF-8.   
I also get a whole bunch of gibberish:

   ���F�'
��$�d�-��[+�5���7�Q�WoIt��s��r�d��OV�|ټ������7��V·BI�r<�^_n�DZ����4��+M
p�|��B�Ħ�k�ɣ�(�%u����岅�FZo����c�WK�qyy�j���KV�Eԫ:����T���n�Euocg)��
��e�jr�ч���N��������#�T~���=����EoqS(§)'����C
J��di��͹�r�u���2�8{X^WJKKKs�s�f}J��:�Q���Y�ԗ;>[3��1�Qp[n�               
��p�&gt;r��W���WVZ��9]D�\��]W��rjm�J-�w��L�f�)A¼8���{r[y��;�NIF�GM�n��ߩ��z��^
�ֳ��a=��l��o�ѱ���5+�&amp;ӽ�M��8����Q���&lt;3KI����۞w��V����C�Z���#
                                                          $�X�e���
��OG����j��^�%H6�@��n
                     ��c9��M��.@�7��6.!
                                       ��x���Wx�A��m��[�co��>   .��
O��NI�Z'�_"�h�gzm5%��wZ�7���L���-n\J��+�K���;�|���m)�_������֍���M���a#�
V���5k�p�e�A}�#[a�h�N������ғ]�$�4����*�s2;A�*t�ݖ����g�r�;k��I��读o�p}��}�G^�
�w�鲾cR�?�.���sl�r�~�
�䮞�O���:��E^6�\�oCW&ɩ�   

Can someone please help me out? Thanks!

标签: flutterdart

解决方案


  • Create a folder called assets in the main path of your project.
  • Put the image inside the folder.
  • Declare your image in your Pubspec.yaml like this:
assets:
    - assets/backgroundpic.jpeg

  • You must add the full path of your pic in your code:
image: AssetImage('assets/backgroundpic.jpeg');

推荐阅读