I have a home page called home.dart, where I have defined my other pages like so (I'm using a bottom navbar): `
late final List<Widget> _pageOptions;
@override
void initState() {
appBarColor = colors[4];
initializeCoins();
_pageOptions = [
ProScreen(Values.coins.toString()),
CatScreen(),
NotScreen(),
FavScreen(),
HomeScreen(),
];
super.initState();
}
`
I'm receiving some data from an API and showing it in home.dart's appBar and it works fine. the thing is when I'm trying to show the same thing in ProScreen (passing the same variable I'm showing in appbar to ProScreen's constructor) it doesn't work and shows it's defaut values instead (0) What should I do?
class Values{
static int coins = 0;
...
}
Future<void> initializeCoins() async {
_prefs =await SharedPreferences.getInstance();
var response = await http.get(Uri.parse(Values.url Values.user_endpoint),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ${_prefs?.getString('token')}',
}
);
setState(() {
coinsLoaded = true;
Values.coins = (jsonDecode(response.body)['user']['score']);
});
}
CodePudding user response:
I think this should work
Create a async function that prepare pages (initPages), it will wait until Values initialize, and after that do a setState and create your pages
Like this:
late final List<Widget> _pageOptions;
@override
void initState() {
initPages();
super.initState();
}
initPages() async {
appBarColor = colors[4];
await initializeCoins();
setState(() {
_pageOptions = [
ProScreen(Values.coins.toString()),
CatScreen(),
NotScreen(),
FavScreen(),
HomeScreen(),
];
});
}
CodePudding user response:
That's because you're passing different value than you think. When you download data it works correctly the first time because you're using data received, but when creating new screen you take static value that you've created previously which is 0.
You explicitly state that this is a new 'instance' of the class Values when doing Values.coins.toString()
.
Try returning int that you're receiving Future<int> initializeCoins() async {
and return jsonDecode(response.body)['user']['score']
. With this you can do something like that:
@override
void initState() async {
appBarColor = colors[4];
int coins = await initializeCoins();
_pageOptions = [
ProScreen(coins.toString()),
CatScreen(),
NotScreen(),
FavScreen(),
HomeScreen(),
];
super.initState();
}