How to Deal With Unwanted Widget Build In Flutter??

· 5 min read
How to Deal With Unwanted Widget Build In Flutter
How to Deal With Unwanted Widget Build In Flutter

Build Method describes the part of the user interface represented by this widget. The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change. So in today’s article, we will go through How to Deal With Unwanted Widget Build In Flutter.

How to Deal With Unwanted Widget Build In Flutter?

The build method is designed in such a way that it should be pure/without side effects. This is because many external factors can trigger a new widget build, such as:

  • Route pop/push
  • Screen resize, usually due to keyboard appearance or orientation change
  • Parent widget recreated its child
  • An Inherited Widget the widget depends on Class.of(context) pattern change.

This means that the build method should not trigger an HTTP call or modify any state. Instead of preventing build calls, you should make your build method pure, So that it can be called anytime without impact.

In the case of your example, you’d transform your widget into a Stateful widget then extract that HTTP call to the initState() of your State:

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  Future<int> future;

  @override
  void initState() {
    future = Future.value(42);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: future,
      builder: (context, snapshot) {
        // create some layout here
      },
    );
  }
}

The easiest way is to use dart const constructors:

@override
Widget build(BuildContext context) {
  return const DecoratedBox(
    decoration: BoxDecoration(),
    child: Text("Hello World"),
  );
}

Thanks to that const keyword, the instance of DecoratedBox will stay the same even if the build were called hundreds of times.

But you can achieve the same result manually:

@override
Widget build(BuildContext context) {
  final subtree = MyWidget(
    child: Text("Hello World")
  );

  return StreamBuilder<String>(
    stream: stream,
    initialData: "Foo",
    builder: (context, snapshot) {
      return Column(
        children: <Widget>[
          Text(snapshot.data),
          subtree,
        ],
      );
    },
  );
}

So in this example when StreamBuilder is notified of new values, the subtree won’t rebuild even if the StreamBuilder/Column Widget does.

You can prevent unwanted build calling, using this way:

  • Create child Stateful class for an individual small part of UI
  • Use Provider library, so using it you can stop unwanted build method calling

In these below situation build method call

  • After calling initState()
  • After calling didUpdateWidget()
  • When setState() is called.
  • When the keyboard is open
  • and When screen orientation changed
  • Parent Widget is built then child widget is rebuild

Flutter also has ValueListenableBuilder<T> class. It allows you to rebuild only some of the widgets necessary for your purpose and skip the expensive widgets.

You can see the documents here ValueListenableBuilder flutter docs
or just the sample code below:

 return Scaffold(
  appBar: AppBar(
    title: Text(widget.title)
  ),
  body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('You have pushed the button this many times:'),
        ValueListenableBuilder(
          builder: (BuildContext context, int value, Widget child) {
            // This builder will only get called when the _counter
            // is updated.
            return Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Text('$value'),
                child,
              ],
            );
          },
          valueListenable: _counter,
          // The child parameter is most helpful if the child is
          // expensive to build and does not depend on the value from
          // the notifier.
          child: goodJob,
        )
      ],
    ),
  ),
  floatingActionButton: FloatingActionButton(
    child: Icon(Icons.plus_one),
    onPressed: () => _counter.value += 1,
  ),
);

Conclusion:

Thanks for being with us on a Flutter Journey!!!

So in this article, we have been through how to deal with unwanted widget build in flutter.

Do let us know if you need any assistance with flutter development.?? We would love to assist you.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply