首页 > 解决方案 > 颤振 setState 不会重新渲染我的孩子有状态小部件

问题描述

这是我的代码

   var _showGoogleMaps = false;

   @override
   void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 2000), () => setState(() {
    _showGoogleMaps = true;
    } ));

   }

   @override
   Widget build(BuildContext context) {

  return 
  // example 1

  /

/ _showGoogleMaps ? Container(height: 500, color: Colors.blue)
      //          : Container(height: 500, color: Colors.red);

  // example 2
  FullImageView(
  imgCodeVal: imgCodeVal,
  child: Container(height: 500, color: _showGoogleMaps ? Colors.blue : Colors.red));
}  


class FullImageView extends StatefulWidget {
  final ValueListenable<String> imgCodeVal;
  final Widget child;
  FullImageView({Key key, this.imgCodeVal, this.child}) : super(key: key);

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

class _FullImageViewState extends State<FullImageView> {
  String _imgCode;
  Widget _child;

  double _height = 0;

  bool _showImage = false;

 @override
 void initState() { 
    super.initState();
   _child = widget.child;
}

   @override
  Widget build(BuildContext context) {
    return Stack( children: [
      _child
  )))))
]);
 }
}

在示例 1 中,容器颜色会在 2 秒后从红色变为蓝色。

但在示例 2 中,颜色为红色且未更改。FullImageView 只是一个普通的有状态小部件

我不明白为什么。任何人都知道原因。谢谢

标签: flutterwidgetsetstatestateful

解决方案


推荐阅读