Reputation: 1656
At the HompePage, am navigating to Settings page with;
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) => Settings()));
the Settings()
page contains an int
input to allow user specify the number of posts they want to see at the HomePage
. When users input the number and form.save, the value is stored in SharedPreferences
. But when the user go back to the HomePage
, the initial number of post still there. I want the HomePage
state to refresh so that the number of post the user specify at the Settings Page will take effect immediately the form is saved.
Below is some snippets of my code;
This is the form _submit
on Settings()
page,
_submit() async {
final form = _formKey.currentState;
SharedPreferences prefs = await SharedPreferences.getInstance();
if (form.validate()) {
prefs.setInt('defaultField', newva);
form.save();
final mysb = SnackBar(
duration: Duration(seconds: 1),
content: new Text(
'Data Saved Successfully',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
backgroundColor: Colors.red,
);
_scaffoldKey.currentState?.showSnackBar(mysb);
myHomePageState.setState(() {
newSULength = newva;
});
print('Done for $newva');
}
}
This is my MyHomePage()
MyHomePageState myHomePageState = new MyHomePageState();
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => new MyHomePageState();
static MyHomePageState of(BuildContext context){
final MyHomePageState navigator = context.ancestorStateOfType(const TypeMatcher<MyHomePageState>());
assert(() {
if(navigator == null) {
throw new FlutterError('Error occoured');
}
return true;
}());
return navigator;
}
}
class MyHomePageState extends State<MyHomePage> {
int newSULength = 0;
void initState() {
// TODO: implement initState
super.initState();
loadDF();
}
set newle(String value) => setState(() => _string = value);
loadDF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
newSULength = (prefs.getInt('defaultField') ?? 5);
for (int i = 0; i < newSULength; i++) {
\\todos
}
});
print('Done');
}
}
Upvotes: 0
Views: 2992
Reputation: 21728
You can use callbacks
to indicate the HomePage
that the Settings
page changed some value in shared preference. Refer this
Upvotes: 1