I want to change the value of an integer in another class and rebuild this class so the bottom navigation bar items will change according to the integer
Here's the main class were the bottom navigation bar exists and the condition to hide or show the items :
class Home extends StatefulWidget {
static int showCard = 0;
@override
_HomeState createState() => _HomeState();
}
@override
Widget build(BuildContext context) {
...
//the items to show and hide according to int showcard
if (Home.showCard == 0)
BottomNavigationBarItem(
icon: Icon(
Icons.person_outlined,
),
title: Text(
'Profile',
),
),
if (Home.showCard != 0)
BottomNavigationBarItem(
icon: Icon(Icons.settings),
title: Text(
'Settings',
),
)
And here's the second class where i want to change the value of showcard to hide the profile section ad show the setting , i'm calling set state with on pressed in this class it's changing the value but not rebuilding the main class :
class Homehome extends StatefulWidget {
const Homehome({Key? key}) : super(key: key);
@override
_HomehomeState createState() => _HomehomeState();
}
class _HomehomeState extends State<Homehome> {
@override
Widget build(BuildContext context) {
...
child: RaisedButton(
onPressed: () {
setState(() {
Home.showCard = 1;
});
Navigator.of(context)
.push(MaterialPageRoute(
builder: (context) => Green(),
));
},
any suggestions ?
CodePudding user response:
You don't need to change the state. You should only update the state when you want to change something inside a widget, for instance a Text value or something like that.
Every time you change a value, it changes. If you want to change a 'visible value', then you have to change the state by setState method.
CodePudding user response:
It sounds like you need to get a better understanding of state.
Widgets in Flutter live in a hierarchy. You should have a state in one widget, and then child widgets update based on this state. You can pass state changes down to child widgets using parameters.
Also, prefer to use proper data types for the situation. Don’t use a numerical data type like an int
for showing or hiding a widget; use a bool
(true
or false
).
CodePudding user response:
You can use callback functions: have a look at this solution. https://stackoverflow.com/a/59832932/16479524
upvote if helpful :)