【问题标题】:how to access passed value from widget in initializer flutter如何在初始化程序颤动中从小部件访问传递的值
【发布时间】:2021-12-25 08:12:24
【问题描述】:

我正在从另一个页面获取 imageUrl。我想使用“theimage”中的“imageUrl”,但我无法访问它。我正面临这个错误。

无法在初始化程序中访问实例成员“widget”。 尝试用不同的表达式替换对实例成员的引用

class ProductCard extends StatefulWidget {
  final String imageUrl;
  ProductCard(
      {this.imageUrl,});

  @override
  State<ProductCard> createState() => _ProductCardState();
}

class _ProductCardState extends State<ProductCard> {

  // I can not access widget.imageUrl in here
    final theImage = Image.network("${widget.imageUrl}", fit: BoxFit.cover);

    /// Did Change Dependencies
    @override
    void didChangeDependencies() {
      precacheImage(theImage.image, context);
      super.didChangeDependencies();
    }
  @override
  Widget build(BuildContext context) {

    return Container(
            child:theImage;
            );
   }
}

【问题讨论】:

    标签: firebase flutter widget


    【解决方案1】:

    您正在使用命名构造函数ProductCard 使imageUrl 必需为空,或提供默认值。

     const ProductCard(
          {required this.imageUrl,});
    

    并使用initState 进行初始化。

      late final Image theImage;
    
        @override
      void initState() {
          theImage = Image.network("${widget.imageUrl}", fit: BoxFit.cover);
        super.initState();
      }
    

    接下来从theImage 的末尾删除; 或使用,

      @override
      Widget build(BuildContext context) {
        return Container(child: theImage);
      }
    

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 2022-09-25
      • 2022-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 2021-11-26
      相关资源
      最近更新 更多