Flutter提供者未在didChangeDependencies中提供更新的值

时间:2020-01-13 15:36:41

标签: flutter dart flutter-provider

使用Provider.of中的didChangeDependencies无法获得最新值

提供小部件

  int counter = 0;

  @override
  void initState() {
    super.initState();

    FirebaseAuth.instance.onAuthStateChanged.listen((FirebaseUser user) async {
      if (user != null) {

        // Intentionally adding a delay to allow enough time to reproduce the issue
        await Future.delayed(Duration(seconds: 1));

        setState(() {
          counter += 1;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    debugPrint('providing $counter');

    return Provider.value(
      value: counter,
      child: MaterialApp(/* routes here */),
    );
  }

然后在Future到期之前立即导航到使用路线

正在使用的小部件

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    final provided = Provider.of<int>(context);
    debugPrint('Dep changed $provided');
  }

结果

I/flutter ( 5074): 0
I/flutter ( 5074): Dep changed 0
I/flutter ( 5074): 1
I/flutter ( 5074): Dep changed 0

据我了解,在Provider.of中调用didChangeDependencies应该会获得最新的价值。相反,在点击消费小部件后, 会以正确的提供值再次调用didChangeDependencies

在提供者^ 4.0.1上测试,抖动稳定的频道

0 个答案:

没有答案