提供程序在flutter中总是获取valuenotifier的旧值

q1qsirdb  于 2023-04-22  发布在  Flutter
关注(0)|答案(1)|浏览(107)

在这个演示中,当通知程序被更改时,provider下的Test6小部件将总是在更改通知程序后获得旧值,正如日志所示。

是什么让此Provider.of始终获取旧值?

class Test6 extends StatelessWidget {
  const Test6({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    int value = Provider.of<int>(context, listen: false);
    print('Test6 read from Provider.of:$value');
    return Text('$value');
  }
}

class Test5 extends StatelessWidget {
  Test5({Key? key}) : super(key: key);
  ValueNotifier<int> notifier = ValueNotifier(1);
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        ValueListenableBuilder(
            valueListenable: notifier,
            builder: (_, value, __) {
              print(' _value:$value');
              int intValue = notifier.value;
              print(' notifier.value:$value');
              return Provider(
                create: (context) => intValue,
                child: Test6(),
              );
            }),
        TextButton(
            onPressed: () {
              print('Test5 change notifier');
              notifier.value = notifier.value + 1;
              print('Test5 after :$notifier');
            },
            child: Text('add 1')),
      ],
    );
  }
}

日志在这里:

flutter:  _value:1
flutter:  notifier.value:1
flutter: Test6 read from Provider.of:1
flutter: Test5 change notifier
flutter: Test5 after :ValueNotifier<int>#d2647(2)
flutter:  _value:2
flutter:  notifier.value:2
flutter: Test6 read from Provider.of:1
wvt8vs2t

wvt8vs2t1#

将密钥添加到提供程序,

Provider(
   key: ValueKey(intValue),
    )

相关问题