The method setState() cannot be refreshed effectively in ChangedNotifier when update one of a data in List.

This issue has been created since 2022-11-23.

Steps to Reproduce

  1. Git repo on the code sample
  2. Click FloatingButton, and update one of gradient color.
  3. Click twice it refresh once.

Expected results:

It should be refreshed anyway.

Actual results:

I try to change the color of the Gradient dynamically, but when only one data is updated, the data is updated in even times, and the widget not refresh in odd times.

Code sample
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    _counter++;
    /// This update is nice.
    // GradientNotifier.instance().colors = <Color>[Colors.primaries[_counter % Colors.primaries.length], Colors.red, Colors.yellow];

    /// TODO Question  Why state set incorrectly. Odd time not work.
    GradientNotifier.instance().setColor(0, Colors.primaries[_counter % Colors.primaries.length]);
    // GradientNotifier.instance().setColor(1, Colors.accents.reversed.toList()[_counter % Colors.primaries.length]);
  }

  void _setState() {
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    GradientNotifier.instance().addListener(_setState);
  }

  @override
  void dispose() {
    GradientNotifier.instance().removeListener(_setState);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: DecoratedBox(
        decoration: BoxDecoration(
            gradient: LinearGradient(
          colors: GradientNotifier.instance().colors,
        )),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'You have pushed the button this many times:',
              ),
              Text('${GradientNotifier.instance().colors[0].toString()}, ${GradientNotifier.instance().colors[1].toString()}'),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

class GradientNotifier with ChangeNotifier {
  GradientNotifier._();

  static final GradientNotifier _instance = GradientNotifier._();

  factory GradientNotifier.instance() => _instance;

  /// Gradient Colors
  List<Color>? _colors;

  List<Color> get colors => _colors ?? <Color>[Colors.blue, Colors.white];

  set colors(List<Color> colors) {
    _colors = colors;
    notifyListeners();
  }

  setColor(int index, Color? color) {
    if (color == null) return;
    colors[index] = color;
    print("after $colors");
    List<Color> temp = colors.toList(growable: true);
    _colors = temp;
    notifyListeners();
  }
}
Logs
exaby73 wrote this answer on 2022-11-24

Hello @davidzou. This is working as expected. Basically, Flutter is trying to optimize builds. The List you are providing has the same memory address so Flutter thinks the value has not changed and therefore doesn't update the UI. You can fix it by wrapping it in `List.from':

decoration: BoxDecoration(  
  gradient: LinearGradient(
    colors: List.from(GradientNotifier.instance().colors),
  ),
),

Since this is working as intended, I am closing this issue. Thank you

davidzou wrote this answer on 2022-11-25

Thanks @exaby73

More Details About Repo
Owner Name flutter
Repo Name flutter
Full Name flutter/flutter
Language Dart
Created Date 2015-03-06
Updated Date 2022-12-10
Star Count 147243
Watcher Count 3561
Fork Count 23950
Issue Count 11325

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
Default validators are not executed when defining a custom validator for another field 2 2022-07-22 2022-11-02
Misleading usage of a crippled function in the documentation examples 2 2020-12-03 2022-12-01
[BUG] Function onOpen 1 2021-10-13 2022-09-26
hard page flip for all pages 1 2021-02-10 2022-08-17
Select tilde and arobase when double-clicking 2 2022-10-26 2022-11-16
Possible ways to identifying different windows 1 2022-11-04 2022-11-16
Shortcut "Open in Tilix"? what is it? 0 2022-11-01 2022-11-16
Only "Enter" works in sychronize input mode 1 2022-10-27 2022-11-16
Quake-style terminal doesn't cover full width of monitor on 100% width 0 2022-11-02 2022-11-16
Crash when using an old version of Waystones. (update to latest to fix) 8 2021-11-20 2022-08-05
Cannot black list specific structures from The Beginning 5 2021-11-20 2022-10-20
Trigger first auto-fetch faster 1 2021-06-14 2022-10-16
ClickFix won't start with Windows 10 as Administrator 3 2021-01-09 2022-11-13
Timeout running Remove-AzImageBuilderTemplate 1 2021-02-04 2022-12-01
[Kernel 5.17.15] `sha256.c:(.text.unlikely+0xc)`: undefined reference to `fortify_panic` 2 2022-10-13 2022-12-01
00262307 - PCB yol kalınlıkları 0 2021-09-22 2022-11-23
About the data set directory structure 1 2020-10-20 2022-11-29
Issues with placement 0 2022-03-25 2022-11-12
Predicates does not work in Egraph saturation? 8 2022-04-04 2022-11-27
Bug: 'Rapid7 Insightconnect ' folder name invalid on Windows 0 2021-08-08 2022-11-20
Installation Manager 3 2021-10-11 2022-11-16
Feature Request: SMS/calls extraction on non rooted device with temporary app 0 2021-11-06 2022-11-27
On using `-l`, `setfont` and custom fonts in Ubuntu (and possibly Debian) 1 2021-04-03 2022-12-05
Question: Can you use saved PaymentMethods for later use in PaymentSheet ? 0 2022-02-04 2022-10-23
Park and Rides locations not shown. 0 2022-04-21 2022-10-30
Don't show tag aliases in tags list 0 2022-11-27 2022-11-29
build wrong unicode html 2 2021-11-01 2022-10-20
MIT-SHM error solutions 6 2018-03-21 2022-11-19
Screen shot is out of date. 0 2022-02-17 2022-11-05
Give the option to auto-generate a basic Web.config file when trying to deploy a full-framework app 4 2021-06-22 2022-11-21
Replace elliptic with noble-secp256k1 2 2022-09-19 2022-12-03
Giveaway Description Message 3 2022-02-03 2022-10-28
Connect to fresh drupal 8 6 2019-01-31 2022-11-02
Policy fail to restrict user in mc client 14 2021-11-23 2022-11-28
[Bug]: The `EndOfRouteViewController` set the view bottom as safe area bottom 0 2022-03-01 2022-11-30
flatMap(.latest) and delayed inner SignalProducer 4 2019-08-02 2022-12-10
Can `com.typesafe:ssl-config-core:0.4.3` be updated 3 2022-08-10 2022-09-04
Key error 'id' when doing PUT request 1 2015-10-21 2022-12-10
目标端MongoDB4.2 无法同步 1 2021-03-04 2021-12-30
DISABLED test_barrier_group (__main__.TestDistBackendWithSpawn) 2 2022-01-02 2022-10-16
Checking for Objective-C compatibility 1 2022-05-23 2022-11-21
os.path.lexists翻译错误 1 2021-10-21 2022-01-16
config parsing in send_gearman produces errors in the output 1 2022-10-13 2022-10-22
[RHEL 9] - Deployment 1 2022-10-28 2022-10-22
A11y_VisualStudioCodeClient_Editor_StatusMessages: Screen reader does not announce confirmation of the folding and unfolding action of code. 1 2022-01-28 2022-10-03
2.5.0 TypeScript functions get unnecessary wrapped 8 2021-11-25 2022-12-08
ImportError: DLL load failed: El sistema operativo no puede ejecutar %1. 8 2020-01-25 2022-10-13
Group metrics per request (breakdown table) 0 2020-05-13 2022-10-29
Persistent Volumes permission issue for 2+ node clutsters 21 2021-08-27 2022-11-27
Add comment to one line of example 0 2020-07-19 2022-11-21