Error: Not a constant expression. (Flutter)

17,675

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.

Share:
17,675
Tony
Author by

Tony

CodeforLife

Updated on December 15, 2022

Comments

  • Tony
    Tony over 1 year

    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.

  • Tony
    Tony over 4 years
    Unfortunately I gives me anaother error Arguments of a constant creation must be constant expressions. Try making the argument a valid constant, or use 'new' to call the constructor.
  • lyio
    lyio over 4 years
    I guess you have to remove the const before the FullScreenWrapper as well.
  • Ulysses Alves
    Ulysses Alves over 3 years
    I think I might have copied my code from somewhere and didn't realize it had a leading "const" keyword in front of one of my widgets. Removing it solved the problem.
  • Zionnite
    Zionnite about 2 years
    accurate... Thanks for this