'Dart 'the constructor being called isn't a const constructor' when using FlexibleSpaceBar background property

When using the FlexibleSpaceBar widget in flutter I am unable to set the background property. According to the docs it's supposed to be a Widget.

From the docs:

{Widget background} Shown behind the [title] when expanded. Typically an [Image] widget with [Image.fit] set to [BoxFit.cover].

When I try to set the property by using the Image.asset functions it shows an error 'The constructor being called isn't a const constructor. Try using 'new' to call the constructor.'. So obviously I tried using the 'new' keyword which didn't fix it either. I also tried with different Widgets but all seem to throw the same error.

I used the following code:

flexibleSpace: FlexibleSpaceBar(
   title: Text('Demo'),
   background: Row(
           children: <Widget>[Text('DEMO')],
   ),
   // background: Image.asset('images/lake.jpg',
   //     width: 500, height: 300, fit: BoxFit.cover),
) 

When using the Image asset outside the FlexibleSpaceBar it's working fine! At this point I'm not sure it's a bug or doing something entirely wrong.

Versions: flutter: 1.7.8+hotfix.4 dart: 2.4.0



Solution 1:[1]

As the comment suggest, this kind of error was due to const used to construct an object somewhere in your code that doesn't provide a const constructor.

flexibleSpace: FlexibleSpaceBar(
   title: Text('Demo'),
   background: Row(
           children: <Widget>[Text('DEMO')],
   ),
   // background: Image.asset('images/lake.jpg',
   //     width: 500, height: 300, fit: BoxFit.cover),
)

Checking the code that you've provided, most probably the error could be produced when you are assigning a constant FlexibleSpaceBar() widget to flexibleSpace parameter which isn't supposed to be constant.

See example below:

flexibleSpace: const FlexibleSpaceBar(
   title: Text('Demo'),
   background: Row(
           ...
   ),
   ...
)

But since this is not the case, there should be somewhere in your code that you need to check.

I suggest to use Flutter debugging tools, to isolate the part of the code that causes a problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MαπμQμαπkγVπ.0