【问题标题】:Error: Not a constant expression in Flutter错误:不是常量表达式。 (扑)
【发布时间】:2020-03-09 00:05:25
【问题描述】:

我使用来自library 的演示,它运行良好。 但是当我在我的项目中实现时,我在这一行得到了错误

错误:不是常量表达式。常量 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,但无济于事。

【问题讨论】:

    标签: flutter dart assets photo


    【解决方案1】:

    这里const AssetImage(snapshot.data[index]) 你正在使用const 构造函数。编译器需要一个编译时间常量,并抱怨因为您传入的参数不是常量,而是取决于 snapshot.data 的运行时值。

    如果您只是删除 const 关键字,它应该可以正确编译。

    【讨论】:

    • 不幸的是我给了我另一个错误Arguments of a constant creation must be constant expressions. Try making the argument a valid constant, or use 'new' to call the constructor.
    • 我猜你也必须删除FullScreenWrapper之前的const
    • 我想我可能从某个地方复制了我的代码,但没有意识到它在我的一个小部件前面有一个前导的“const”关键字。删除它解决了问题。
    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 2017-03-30
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多