0

I want to use the _count variable in another widget. I can't access _count variable with provider

class Hamburger extends StatefulWidget {
  const Hamburger({super.key});

  @override
  State<Hamburger> createState() => _HamburgerState();
}

class _HamburgerState extends State<Hamburger> {
  int _count = 1;
Salih
  • 11
  • 3

1 Answers1

0

The issue is that you are trying to access _count in a separate class without providing context to the Provider. To access the value of _count using Provider, you need to wrap the _HamburgerState widget in a ChangeNotifierProvider and expose _count as a listenable property.

This is an example:

import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';

class Hamburger extends StatefulWidget {
  const Hamburger({Key key}) : super(key: key);

  @override
  State<Hamburger> createState() => _HamburgerState();
}

class _HamburgerState extends State<Hamburger> {
  int _count = 1;

  void incrementCount() {
    setState(() {
      _count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: this,
      child: Container(),
    );
  }
}

class CountNotifier extends ChangeNotifier {
  int _count;

  int get count => _count;

  set count(int value) {
    _count = value;
    notifyListeners();
  }
} 
Bruno Eigenmann
  • 346
  • 3
  • 16
  • @override Widget build(Buildcontext context){ Color coloricon = Provider.of(context).coloricon; return ChangeNotifierProvider.value() } } '_HamburgerState' doesn't conform to the bound 'ChangeNotifier?' of the type parameter 'T'. Try using a type that is or is a subclass of 'ChangeNotifier?'. – Salih Feb 07 '23 at 20:08