Search code examples
flutterdartassetsphoto

Error: Not a constant expression in Flutter


I using the demo from this library and it works perfectly. But when I implement in my project, I get error on this line

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

My Container is wrapping in 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
                                    )));
               },
       ),

Here the printed value

The value is /storage/emulated/0/Android/data/xxx/files/Pictures/scaled_1572364487252xxx.jpg

If I remove the const, I get others error

Arguments of a constant creation must be constant expressions. Try making the argument a valid constant, or use 'new' to call the constructor.

I even tried using new but to no avail.


Solution

  • Here const AssetImage(snapshot.data[index]) you are using a const constructor. The compiler is expecting a compile time constant and is complaining because the arguments you are passing in are not constant but depend on the runtime value of snapshot.data.

    If you simply remove the const keyword it should compile without errors.