Home > other >  Flutter: How to stop Container recreating its child when decoration is changed
Flutter: How to stop Container recreating its child when decoration is changed

Time:06-03

I have widgets like those below where one is a child of a container that sometimes has a decoration and sometimes doesnt. For some reason the child is getting recreated instead of just having its build method rerun.


class StatefulReproduction extends StatefulWidget {
  const StatefulReproduction({Key? key}) : super(key: key);

  @override
  _StatefulReproductionState createState() => _StatefulReproductionState();
}

class _StatefulReproductionState  extends State<StatefulReproduction>{
  var timer;
  var counter = 0;
  @override
  initState() {
    print("setup reproduction");
    super.initState();
    timer = Timer.periodic(new Duration(seconds: 1), (timer) {
      setState(() {
        counter = 1   counter;
      });
    });
  }

  @override
  dispose(){
    print("cleaned up reproduction");
    super.dispose();
    timer.cancel();
  }

  @override
  build(BuildContext context) {

    return Container(
        child: StatefulChild(),
        decoration:  BoxDecoration(border: (counter % 2 == 0) ? Border.all(color: const Color.fromARGB(255, 0, 0, 255)): null)
    );
  }
}

class StatefulChild extends StatefulWidget {
  StatefulChild({super.key});

  @override
  _StatefulChildState createState() => _StatefulChildState();
}

class _StatefulChildState extends State<StatefulWidget>{

  @override
  initState() {
    super.initState();
    print("init state called");
  }

  @override
  build(BuildContext context) {
    return Text("hi");
  }
}

I want the stateful child to only print something once but instead its printing on every time tick which I think means its being recreated but I dont understand why or how I can stop this.

CodePudding user response:

Try to use Border.all(color: Colors.transparent) instead of null. You will not show a border on the screen but initState in the child widget will not be called

CodePudding user response:

Try to add const keyword before the StatefulChild's constructor. And also mark this widget as const inside a Container:

return Container(
  child: const StatefulChild(),
  decoration: BoxDecoration(border: (counter % 2 == 0) ? Border.all(color: const Color.fromARGB(255, 0, 0, 255)): null)
);
  • Related