为什么我的Flutter Riverpod计数器没有在UI上更新?

4uqofj5v  于 2023-05-23  发布在  Flutter
关注(0)|答案(1)|浏览(169)

主Flutter计数器

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'data/providers.dart';

void main() {
  runApp(
    // For widgets to be able to read providers, we need to wrap the entire
    // application in a "ProviderScope" widget.
    // This is where the state of our providers will be stored.
    ProviderScope(
      child: MyApp(),
    ),
  );
}

class MyApp extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    var men = ref.watch(populationController).men.toString();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Example')),
        body: Center(
            child: Column(
          children: [
            Text("Amount of men is $men"),
            IconButton(
                onPressed: () {
                  ref.read(populationController.notifier).increaseMen();
                },
                icon: const Icon(Icons.plus_one))
          ],
        )),
      ),
    );
  }
}

定义riverpod类的文件

import 'package:flutter_riverpod/flutter_riverpod.dart';

class PopulationTracker {
  int women = 0;
  int men = 0;
}

class PopulationNotifier extends StateNotifier<PopulationTracker> {
  PopulationNotifier() : super(PopulationTracker());

  void increaseMen() {
    state.men += 1;
  }

  void increaseWomen() {
    state.women += 1;
  }

  void minusWomen() {
    state.women -= 1;
  }

  void minusMen() {
    state.men -= 1;
  }
}

final populationController =
    StateNotifierProvider<PopulationNotifier, PopulationTracker>(
        (ref) => PopulationNotifier());

我试着更新我的人口跟踪器的状态使用riverpod和flutter。我对这一点很陌生,不能弄清楚为什么UI上的计数器不更新,如果我打印状态的值到控制台,我可以看到值更新。
我希望计数器在UI上更新为+1,但它没有。

为什么计数器在UI上不更新?

csbfibhn

csbfibhn1#

状态对象没有更改标识。只是变异而已。变异不足以向侦听器发出新事件。您需要将state视为只读,并使用copyWith这样的操作使其工作。
此外,您应该离开StateNotifier并开始使用Notifier。如果您一直在使用Notifier,我还可以建议您仅为mutate方法添加ref.notifyListeners(),并使其以这种方式工作。
总之,请停止使用ChangeNotifier、StateNotifier和StateProvider。仅支持用于传统目的。

相关问题