Home > other >  How to use Provider to listen to value from another class?
How to use Provider to listen to value from another class?

Time:11-06

in class ListenFirebase I am having a function 'func()' thats increasing counter variable. I want to hear this counter variable in some other widget ProfilePage. I am using Provider. But i think I am writing some wrong code although I cant make it out. When user comes on profile page, in the init method I am calling func method that increases the counter.

@override
  void initState() {
    super.initState();
    ListenFirebase().func();
  }

  @override
  Widget build(BuildContext context) {
    final myCounter = context.watch<ListenFirebase>();
    return ChangeNotifierProvider(
      create: (_) => ListenFirebase(),
      child: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("${myCounter.counter}"),
        
        ],
      )),
    );
  }

This is ListenFirebase class


class ListenFirebase extends ChangeNotifier {
  final user = FirebaseAuth.instance.currentUser;

  int _counter = 0;
  int get counter => _counter;
  setCounter(int value) {
    _counter = value;
    print(_counter);
    notifyListeners();
  }

  final now = DateTime.now();
  final now2 = DateFormat('hh:mm a').format(DateTime.now());
  func() async {
    var count = 0;
    debugPrint("Inside func method ");
    var uid = user?.uid;
    final ref = FirebaseDatabase.instance.ref('uids/$uid/sessions');
    DatabaseEvent event = await ref.once();
    var children = event.snapshot.children;
    for (final object in children) {
      var json = object;
      setCounter(count);
      for (final timeStampe in json.children) {
        if (object.key == "${now.day}-${now.month}-${now.year}") {
          debugPrint(timeStampe.key);
          count  = 1;
          setCounter(count);
        }
      }
    }
  }
}

the func function is working correctly as its incrementing counter to 5 (desired result). But profile page is showing 0 only. any suggestions as to where I am wrong ?

CodePudding user response:

Wrap ProfilePage with ChangeNotifierProvider instead

ChangeNotifierProvider(
  create: (_) => ListenFirebase(),
  child: ProfilePage(),
),

and use read to access ListenFirebase in the page.

initState() {
  super.initState();
  context.read<ListenFirebase>().func();
}
  • Related