Flutter:如何在装饰更改时停止容器重新创建其 child

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

我有像下面这样的小部件,其中一个是 child 有时有装饰有时没有的容器。出于某种原因,child 正在重新创建,而不仅仅是重新运行其构建方法。


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");
  }
}

我希望有状态 child 只打印一次,而不是在每次打勾时打印,我认为这意味着它正在重新创建,但我不明白为什么或如何停止它。

尝试在 StatefulChild 的构造函数之前添加 const 关键字。并在 Container:

中将此小部件标记为 const
return Container(
  child: const StatefulChild(),
  decoration: BoxDecoration(border: (counter % 2 == 0) ? Border.all(color: const Color.fromARGB(255, 0, 0, 255)): null)
);

尝试使用 Border.all(color: Colors.transparent) 而不是 null。您不会在屏幕上显示边框,但不会调用子部件中的 initState