Home > Software engineering >  How to prevent child widget redraw when parent widget perform setState()?
How to prevent child widget redraw when parent widget perform setState()?

Time:03-22

I have a ListView inside many stateFull widget of tree, and i cant able to separate from all parent widget. Listview build from streambuilder(firebase). From a large hierarchy of stateFull widget, some of them anytime perform setState widget, then child ListView also redraw and once again it will get data from firebase and also its flickering(blinking)

explain below example

StatefullWidget(
  child:StatefullWidget(
    child:StatefullWidget(
      child:ListView()
    ),
  ),
);

There are three parent widget of Listview(), for user friendly app setState called many time in parent widget.

So i want to avoid flickering and redraw of listView(), even if the parent widget redraw(setState())

CodePudding user response:

https://pub.dev/documentation/provider/latest/provider/Selector-class.html

'selector' of Provider is what you find.

But usually optimizing performance is enough for not blinking. ListView.builder, const Widget, key, etc., https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html#performance-considerations

CodePudding user response:

You should use one of the state management method.

For example with getx package, you can make your widgets stateless and use getx widgets for any updating data.

This is the example of getx usage for default flutter app.

class Home extends StatelessWidget {
  final controller = Get.put(Controller());
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("counter")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            GetBuilder<Controller>(
                builder: (_) => Text(
                      'clicks: ${controller.count}',
                    )),
            ElevatedButton(
              child: Text('Next Route'),
              onPressed: () {
                Get.to(Second());
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: controller.increment(),  
          ),
    );
  }
}
class Second extends StatelessWidget {
  final Controller ctrl = Get.find();
  @override
  Widget build(context){
     return Scaffold(body: Center(child: Text("${ctrl.count}")));
  }
}
  • Related