首页 > 解决方案 > 为什么在变量中调用我的图像资产时出现错误?它说“FlutterError(无法加载资产:)”

问题描述

我正在调用Image.asset()然后调用在我的资产文件夹中保存路径的变量。这是我的代码,这就是将路径分配给 imagePath 变量。我在控制台中打印它并且变量是正确的

  Future getName(String publisherUid) async {
    FirebaseFirestore.instance
        .collection('users')
        .doc(publisherUid)
        .get()
        .then((value) {
      setState(() {
        publisherSchool = value.get('school');
        publisherFirstName = value.get('first-name');
        publisherLastName = value.get('last-name');
        publisherFullName = publisherFirstName + ' ' + publisherLastName;
        publisherUserIcon = value.get('userIcon');
        imagePath = 'assets/images/$publisherUserIcon';
        //print('$imagePath');
      });
    });
  }

然后在此处将其显示在列表图块中

                child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 5),
                  ListTile(
                    leading: Image.asset(imagePath),
                    title: Text(publisherFullName,
                        style: TextStyle(fontSize: 14)),

然后它有一个错误说“FlutterError(无法加载资产:)”。我尝试将变量显示为这样的文本Text(imagePath),它显示正确,请参阅图像以供参考在此处输入图像描述

然后我试图像这样手动显示资产

                    child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 5),
                  ListTile(
                    leading: Image.asset('assets/images/001-panda.png'),
                    title: Text(publisherFullName,
                        style: TextStyle(fontSize: 14)),

当您手动编写图像路径时,我没有收到任何错误这是输出在此处输入图像描述

顺便说一句,这是我在 pubspec.yaml 中的代码。它有适当的缩进,因为如果 pubspec.yaml 中的资产错误,我将无法手动调用路径

  assets:
    - assets/images/

标签: flutter

解决方案


您必须拥有与您在文本中打印的名称完全相同的资产名称。

检查该名称的文件夹“assets/images/”。检查空格或类似的东西。


推荐阅读