Flutter 中的错误:不是常量表达式

26

我使用这个的演示,它可以正常工作。但是当我在我的项目中实现时,我在这一行收到错误提示:

Error: Not a constant expression. const AssetImage(snapshot.data[index]),

我的Container包裹在InkWell中。

  InkWell(
      child: Container(
                 padding:
                      EdgeInsets.zero,
                     height: 150,
                      width: 150,
                      decoration:
                            BoxDecoration(
                                      image: DecorationImage(
                                       image: AssetImage(snapshot.data[index]),
                                            fit: BoxFit .fill),
                                  ),
                           ),
      onTap: () {
               print('The value is ' + snapshot .data[index]);
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder:
                         (context) =>
                            const FullScreenWrapper(imageProvider:const AssetImage(snapshot.data[index]),  // here the error
                                    )));
               },
       ),

这里是打印的值

该值是/storage/emulated/0/Android/data/xxx/files/Pictures/scaled_1572364487252xxx.jpg

如果我删除const,就会得到其他的错误。

常量声明的参数必须是常量表达式。尝试将参数设置为有效的常量,或使用“new”调用构造函数。

我甚至尝试使用new但无济于事。

2个回答

70

在这里,你正在使用一个const构造函数:const AssetImage(snapshot.data[index])。编译器期望一个编译时常量,并且会因为你传入的参数不是常量而发出警告,它取决于snapshot.data的运行时值。

如果你简单地移除const关键字,它应该可以编译通过而没有错误。


不幸的是,它给了我另一个错误:“常量创建的参数必须是常量表达式。尝试使参数成为有效的常量,或使用“new”调用构造函数。” - Tony
5
我猜你需要把 FullScreenWrapper 前面的 const 也删掉。 - lyio
2
我觉得我可能从某个地方复制了我的代码,没有意识到其中一个小部件前面有一个"const"关键字。删除它解决了问题。 - Ulysses Alves
感谢您的这个准确的。 - Zionnite

-4

确保它具有互联网设备或模拟器


这个完全没有意义。 - Tony

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接