How to render child without parent when using setState?

帅比萌擦擦* 提交于 2021-02-08 10:28:01

问题


How to make the code in this answer How to keep changing a Images every 5 seconds in Flutter? to avoid parent rebuild together with child? I want only child do the setState.

I want the setState in Timer does not affect the parent.

I read about how to only rerender the child without parent in this link https://androidpedia.net/en/knowledge-base/51725031/flutter-setstate-of-child-widget-without-rebuilding-parent, but I got confused to implement into the code.

My Objective is like on the image, please click on this link to see the image

The blue circle is logo and the red circle is banner. I want them act like gif. But I cannot do the hardcode and put gif. Because I extract the image from web, like the answer in How to keep changing a Images every 5 seconds in Flutter? did. Therefore, I need to use setState, unfortunately it render the whole apps. How to only rerender the images only?


回答1:


Try this example. In that code i just changed the container color, just replace it with image on your code.

class Sample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
  print("Parent Widget rebuild");

    return SafeArea(
      child: Column(
        children: [
          Container(
            height: 50,
            width: 50,
            color: Colors.red,
          ),
          SizedBox(height: 20),
          ChangingColor(),
        ],
      ),
    );
  }
}

class ChangingColor extends StatefulWidget {
  @override
  _ChangingColorState createState() => _ChangingColorState();
}

class _ChangingColorState extends State<ChangingColor> {
  Timer _timer;
  Color _color;

  @override
  void initState() {
    _timer = Timer.periodic(Duration(seconds: 5), (Timer t) {
      setState(() {
        _color = Colors.primaries[Random().nextInt(Colors.primaries.length)];
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
  print("Child Widget rebuild");

    return Container(
      height: 50,
      width: 50,
      color: _color,
    );
  }

  @override
  void dispose() {
    _timer.cancel();
    _timer = null;
    super.dispose();
  }
}



回答2:


Just extract the part you want to change into a new Stateful Widget.

You can do this by selecting that portion and pressing ctrl shift r in vs code.



来源:https://stackoverflow.com/questions/63717081/how-to-render-child-without-parent-when-using-setstate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!