Flutter/Dart: How to force PrefPage using a ListView to refresh screen?

29 Views Asked by At

I am using the pref library (v 2.7.1) to create a settings page within my flutter app. In particular, in the minimum code sample below, I am using the PrefPage widget which returns a ListView with the items in the children property using ListView(children: widget.children).

Now, when I change the choice in my dropdown item, the page is not refreshed even though I call setState() on the changed value currentChoice and the build method gets called. If I go back to the main screen and then back to the PrefPage however, it is updated.

Here is the state part of my minimal app:

class _MyAppState extends State<MyApp> {

  int currentChoice = 0;

  void _updateChoice(int? value) {
    setState(() {
      currentChoice = value!;
    });
  }

  @override
  Widget build(BuildContext context) {
    return PrefService(
      service: widget.service,
      child: MaterialApp(
        home: Scaffold(
            appBar: AppBar(title: const Text('Choice')),
            body: PrefPage(
            children: [PrefPageButton(
                key: UniqueKey(),
                page: PrefPage(cache: false, key: UniqueKey(), children: [
                  PrefDropdown(
                      onChange: _updateChoice,
                      items: const [DropdownMenuItem(value: 0, child: Text("Item 1")), DropdownMenuItem(value: 1, child: Text("Item 2"))],
                      pref: 'choice',
                      title: const Text("Title"),
                      key: UniqueKey()),
                  ((currentChoice ?? 1) == 0) ? PrefText(key: UniqueKey(), pref: "myText") : PrefTitle(key: UniqueKey(), title: const Text("myTitle"))
                ]))])),
      ),
    );
  }
}

Interestingly, if I change the PrefDropdown part to a normal DropdownButton by using the following code, it gets even worse as the chosen item is not even shown in the dropdown button (if I choose Item 2 instead of Item 1, the screen still shows Item 1).

DropdownButton(
              onChanged: _updateChoice,
              items: const [DropdownMenuItem(value: 0, child: Text("Item 1")), DropdownMenuItem(value: 1, child: Text("Item 2"))],
              value: currentChoice,
              key: UniqueKey()),
              ((currentChoice ?? 1) == 0) ? PrefText(key: UniqueKey(), pref: "myText") : PrefTitle(key: UniqueKey(), title: const Text("myTitle"))
            ]))])),

Any help on why the view does not refresh even though the build method gets called would be highly appreciated. Thank you!

0

There are 0 best solutions below