why do we need the didUpdateWidget and build method in a statefull widget?

Viewed 450

why do we need the didUpdateWidget method in a state?
Build is called anyway, cant we add the logic there too?
The only difference is, that we dont have a reference to the old widget as paramter or do i miss something?

1 Answers

Yes, you can implement logic in the build method when something is reloaded on your screen. didUpdateWidget is called every time when the corresponding widget is recreated

But, the difference is that, when we can compare some values and based on those values we can take decisions on the app.

Example:

class MyApp extends StatefulWidget {
  int getInitialValue() {
    return 1;
  }
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _currentValue = 10;
  @override
  void didUpdateWidget(MyApp oldWidget) {
      if(oldWidget.getInitialValue() != _currentValue) {
        // Perform animation
        // Fetch data from server
      }
  }
 }

Above is just an example of how we can use didUpdateWidget(), we can do similar stuff for many other scenarios

Related