Two files here: (as to simplify a.dart and b.dart, Classes A and B)
a.dart:
enum CalorieDensity { veryLow, low, medium, high, none }
class A extends StatefulWidget {
const A({
Key? key,
}) : super(key: key);
@override
State<A> createState() => _AState();
}
class _AState extends State<A> {
static CalorieDensity calorieDensity = CalorieDensity.veryLow;
}
b.dart:
enum CalorieDensity { veryLow, low, medium, high, none }
class B extends StatefulWidget {
const B({
Key? key,
}) : super(key: key);
@override
State<B> createState() => _BState();
}
class _BState extends State<B> {
void aSimpleFunction(){
A.calorieDensity = CalorieDensity.veryLow;
}
}
I get this error:
A value of type ‘CalorieDensity (where CalorieDensity is defined in /Users/macbook/Projects/cookedcalories/lib/b.dart)’ can’t be assigned to a variable of type ‘CalorieDensity (where CalorieDensity is defined in /Users/macbook/Projects/cookedcalories/lib/a.dart)’.
Try changing the type of the variable, or casting the right-hand type to ‘CalorieDensity (where CalorieDensity is defined in /Users/macbook/Projects/cookedcalories/lib/a.dart)’
I have not such type of issues for any other static variable.
3
Answers
Solved thanks to Imtiaz Ayon (partially).
By removing the enum from B file is not enough (but this is the way). I also needed to rename the enum to CalorieDensityEnum.
I think because something went wrong by using calorieDensity as a variable per CalorieDensity enum (strange, Dart is a case sensitive language).
I think it’s because you’re defining enum CalorieDensity twice once in a.dart file and once in b.dart file.
Just write the above line once and import that file if you need to use CalorieDensity elsewhere instead of creating a new one.
Problem:
The error is occurring because you are trying to assign an enum defined in one file to a variable of a type of enum defined in another file.
Those two enums are different even though they have the same values.
All enums automatically extend the Enum class and this means that a new Enum object is created when you define an Enum.
You can demonstrate this by defining the
CalorieDensity
enum in two files and comparing them for equality. The result will be false.See below:
Solution:
The solution is to define the enum in one file and import it for use wherever you want to use it.
This ensures you are using the same object for your app’s operations.
I’ll suggest you define it in a file different from your screen files since you use it in multiple screens.