I am realtively new to flutter. HOW TO UPDATE a private variable inside a stateteful flutter widget from another class.
I KNOW ONE WAY IS TO DECLARE IT GLOBALLY but THIS WILL CHANGE MANY THINGS. FOR EXAMPLE: This card is like a button. There are many buttons generated from this class. If I make _temp a global variable; i will lose the sole purpose i.e it being unique for all buttons, all categories, all foods.
another way can be to create a method but i am not sure how t aces it from outside the widget? e.g:
void reset() { _temp = 0; }
Please see the code to understand the problem:
class ReusableCard extends StatefulWidget {
ReusableCard({
required this.itemName,
});
final String? itemName;
@override
State<ReusableCard> createState() => _ReusableCardState();
}
class _ReusableCardState extends State<ReusableCard> {
// HOW TO UPDATE THIS int _temp (BELOW) FROM ANOTHER CLASS?
// I KNOW I CAN DECLARE IT GLOBALLY but THIS WILL CHANGE MANY THINGS.
// FOR EXAMPLE: This card is like abutton. There are many buttons generated from this class. If I make _temp a global variable; i will lose the sole purpose i.e it being unique for all buttons, all categories, all foods.
int _temp = 0;
@override
Widget build(BuildCon .......
CodePudding user response:
You can do that by the following steps:
- Make
_ReusableCardState
and_temp
not private (i.e remove the underscore) - Make
ReusableCard
constructor takes an optional Key and calls its super constructor with this key. like thisReusableCard({Key? key, required this.itemName}) : super(key: key);
- Define a key with the state like this
final GlobalKey<ReusableCardState> reusableCardKey = GlobalKey();
in the class that callsReusableCard
- Pass this key to the
ReusableCard
like thisReusableCard(key: reusableCardKey, itemName: "First Item")
- Now you can use this key (
reusableCardKey
) to modifytemp
throughreusableCardKey.currentState.temp = 28;
CodePudding user response:
try to declare the variable as Static, like this code
void main() {
First.name = 'Bar';
print(First.name);
}
class First {
static String name = 'Foo';
}