Skip to content Skip to sidebar Skip to footer

Problems While Using Flutter Provider Package

I am creating a very simple app to practice flutter provider package. The app has a bulb which on click , should change it's background and the screen's background , using provider

Solution 1:

Try to add listen: false to the provider call :

Provider.of<Data>(context, listen: false).toggle();

Solution 2:

The problem is because Provider constructor has a named parameter listen which is equal to true by default. And this behavour force rebuilding while you use Provider.of() method. It is imposible to call build while current buiding is still active. That is why you suggested to set listen to false because it disables default behavour.

It is better to implement like this:

...

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Consumer<Data>(
      builder: (_, data, __) {
        return Scaffold(
          appBar: AppBar(),
          backgroundColor: data.isOn ? Colors.yellow[100] : Colors.black,
          body: Center(
            child: Column(
              children: <Widget>[
                Stick(),
                Bulb(),
              ],
            ),
          ),
        );
      }
    );
  }
}
...

class _BulbState extends State<Bulb> {
  @override
  Widget build(BuildContext context) {
    return Consumer<Data>(
      builder: (_, data, __) {
        return Container(
          height: 200,
          width: 250,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(100),
              topRight: Radius.circular(100),
              bottomLeft: Radius.circular(30),
              bottomRight: Radius.circular(30)
            ),
            color: data.isOn ? Colors.yellow : Colors.white,
          ),
          child: GestureDetector(
            onTap: () {
              data.toggle();
              setState(() {});
            },
          ),
        );
      },
    );
  }
}

Post a Comment for "Problems While Using Flutter Provider Package"