Home > Back-end >  Rebuild the text of the outer class with Provider
Rebuild the text of the outer class with Provider

Time:03-04

The code below is a simplification of my project. I want it make like: When you push the button, text is rebuilt and increase the number. However, text isn't reloaded. but I detected that the number of count is actualy increased.

Why this text isn't reloaded? Some way to detect changes of other classes?

class CLS extends ChangeNotifier{
    int count = 0;
    void add(int i){
        count  = i;
        notifyListeners();
    }
}

....

class Main extends StatelessWidget{
    Widget txt(){
        return Consumer<CLS>(
          builder: (context, value, _) => Text(value.count.ToString())
        );
    }

    Widget but(int i){
        return ElevatedButton(
          child: Text("Button"),
          onPressed: context.read<CLS>().add(i)
        );
    }

    @override
    Widget build(BuildContext context){
        return Scaffold(
         body: ChangeNotifierProvider(
          create: (BuildContext context) => CLS(),
          child: Column( children: [
            txt(),
            but(1)
        ]));
    }
}

CodePudding user response:

You are using same context for providing and accessing your Provider, so it can't find it. You should use new context to access your provided Provider, because it looks for it's ancessor to find provided Provider. And also you should use that new context to read your Provider from your but() method, like so:

Widget but(int i, BuildContext ctx) {
    return ElevatedButton(
        child: Text("Button"), onPressed: () => ctx.read<CLS>().add(i));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ChangeNotifierProvider(
        create: (BuildContext context) => CLS(),
        child: Builder(builder: (ctx) { // new context(ctx) to find Provider from parent's(ancessor's) context
          return Column(
            children: [
              txt(),
              but(1, ctx), // use that new context in your but method for accessing Provider
            ],
          );
        }),
      ),
    );
  }
  • Related