简体   繁体   English

Flutter:使用 MaterialPageRoute 从无状态小部件到有状态小部件

[英]Flutter: From Stateless Widget to Stateful Widget with MaterialPageRoute

I have a Detail Page as a StatelessWidget .我有一个作为StatelessWidget的详细信息页面。 I have a listview in my Feed.dart.我的 Feed.dart 中有一个listview With click on an Listview Element to you get to the Detail Page.通过单击 Listview 元素,您可以进入详细信息页面。 Now I want to convert the Detail Stateless in a Stateful, but in my feed MaterialPageRoute is now the Error, that the named Parameter shop is not defined.现在我想将无状态的详细信息转换为有状态的,但在我的提要中 MaterialPageRoute 现在是错误,即未定义命名的参数商店。 How do i fix the Error?如何修复错误?

Detail as Stateless无状态的细节

    class Detail extends StatelessWidget {

  final Shop shop;
  Detail({ this.shop });

  var top = 0.0;

  int segmentedControlGroupValue = 0;
  final Map<int, Widget> myTabs = const <int, Widget>{
    0: Text("Item 1"),
    1: Text("Item 2")
  };

my Detail as a Stateful Widget我作为有状态小部件的详细信息

class Detail extends StatefulWidget {
   @override
  _DetailState createState() => _DetailState(Shop());
}


class _DetailState extends State<Detail> {

  final Shop shop;
  _DetailState(this.shop);


  var top = 0.0;

and my feed和我的饲料

class ShopTile extends StatelessWidget {

  final Shop shop;
  ShopTile({ this.shop });

 @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 16),
      child: InkWell(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => Detail(shop: shop)),
        );
      },

It says the first shop is no longer defined in detail.它说第一家商店不再详细定义。 Therefore there is an error.因此存在错误。 When it was a stateless widget, it all still worked.当它是一个无状态的小部件时,它仍然可以工作。 Can you please help me where the error is?你能帮我看看错误在哪里吗?

You should put the constructor in Detail class not in _DetailState :您应该将构造函数放在Detail class 而不是_DetailState中:

class Detail extends StatefulWidget {
  final Shop shop;
  Detail({ this.shop });

   @override
  _DetailState createState() => _DetailState(Shop());
}


class _DetailState extends State<Detail> {

  var top = 0.0;
  Shop shopValue; 

  @override
  void initState() {
    super.initState();
    // access the property 'shop' using 'widget.shop' 
    shopValue = widget.shop
  }
}

Ashok's solution is right. Ashok 的解决方案是正确的。 On your feed needs onTap needs to be changed根据您的提要需要 onTap 需要更改

onTap: () {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Detail(shop: widget[index])),
    );
  },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM