I have a widget called ‘HomePage’ in my application. I gave a pageview to its body and put 2 pages in it. In the Appbar, there is a title that shows the user’s money. on one of the pages there is a button that reduces money. but when I press this button the money is not updated immediately, if I change the page then it is updated. How do I immediately update the money value in the appbar without the page changing?
/////////////////// HOMEPAGE WİDGET ///////////////////
import 'package:flutter/material.dart';
import 'package:flutterapp/demo/user_infos.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(UserInfos.money.toString())),
body: PageView(
children: [
Page1(),
Page2(),
],
),
);
}
}
////////////////////////////////////////////////////////
///// UserInfo class//////
class UserInfos {
static int money = 25000;
...
...
...
...
}
////////////////////////////////////////////////////////////////
//////////// Page1()/////////////////////////////////
class Page1 extends StatefulWidget {
const Page1({super.key});
@override
State<Page1> createState() => _Page1State();
}
class _Page1State extends State<Page1> {
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
setState(() {
UserInfos.money -= 1;
});
},
child: const Text('decrease money')),
);
}
}
I also got help from chatgpt or something, but it didn’t work. I need to change the page or do a hot reolad by doing ‘ctrl+s’. only then the money value is updated
2
Answers
It is not updating the appbar, because your setState() is called on a child widget, and rerender is top down not bottom up, so your child widget is never telling the parent to update.
I updated your code to pass an instance of your UserInfos class to each child that will manipulate it, so that they are updating the value directly. You should however make use of Providers, so that you can have the home widget listen to changes.
The key is rebuild your widgets tree everytime you change your widget’ states
When you do like this
only page1 widget will be scheduled to rebuild. If you want to update changes to your homepage widget, you need to call
setState
inside your homepage widgetThere are many way to do this, the simplest is callback.
Your HomePage widget:
Your Page widget:
Your
_updateState()
function is called inside HomePage widget, so it will rebuild your widget after state changed.A better way is make your state observable
Update money value by
And make your appbar listen for money value changes
Full solution