How to force Flutter to rebuild / redraw all widgets?

后端 未结 9 1606
攒了一身酷
攒了一身酷 2020-12-03 06:32

Is there a way to force Flutter to redraw all widgets (e.g. after locale change)?

9条回答
  •  悲&欢浪女
    2020-12-03 07:01

    Old question, but here is the solution:

    In your build method, call the rebuildAllChildren function and pass it the context:

    @override
    Widget build(BuildContext context) { 
      rebuildAllChildren(context);
      return ...
    }
    
    void rebuildAllChildren(BuildContext context) {
      void rebuild(Element el) {
        el.markNeedsBuild();
        el.visitChildren(rebuild);
      }
      (context as Element).visitChildren(rebuild);
    }
    

    This will visit all children and mark them as needing to rebuild. If you put this code in the topmost widget in your widgets tree, it will rebuild everything.

    Also note you must order that specific widget to rebuild. Also you could have some boolean so that the rebuild of that widget only rebuilds all of its children when you really need it (it's an expensive operation, of course).


    IMPORTANT: This is a hack, and you should only do this if you know what you are doing, and have strong reason to do so. One example where this is necessary is in my internationalization package: i18_extension. As Collin Jackson explained in his answer, you are really not supposed to do this in general.

提交回复
热议问题