background

In my Flutter project, after navigating from component A to component B, component A constantly calls the didUpdateWidget and Build while the soft keyboard is up and down.

The preliminary screening

At first, I thought it was a routing problem, but after investigation, I found that there was a historical problem in Navigator, which would cause the rebuild of oldWidget. After version 1.17, this issue has been fixed and can be avoided without additional developer work.

Correlation analysis

Find clue

We continued to look at a number of possible problems, including menu components, inappropriate calls to MediaQuery, and so on. Start thinking bottom-up: If the component itself does not call setState and does not inherit inheritedWidgets, then unexpected lifecycle function calls must occur because its context is being used unexpectedly somewhere else.

Find the murderer

Search the A component for all the places where context is used, and sure enough, the killer finds:

precacheImage(NetworkImage(Constants.bgUrl), context);
Copy the code

After entering the precacheImage source, it’s easy to find that the context is registered with MediaQuery.maybeof, and the rest is easy to understand: MediaQuery InheritedWidget; When called by the soft keyboard, MediaQueryData changes, and all components registered with mediaQuery.maybeof and mediaQuery.of are updated.

conclusion

  • Deep understanding ofFlutterLife cycle and update logic, always find solutions from source code and principles when encountering related problems.
  • Secure the componentcontext.