简体   繁体   English

在Flutter中为窗口小部件定义自定义参数

[英]Defining a custom parameter to a widget in Flutter

I'm creating a card widget that will be used to create a list of cards. 我正在创建一个卡片小部件,该小部件将用于创建卡片列表。 I want to pass a parameter isLastCard to each card, so that I can increase margin for the last card in the list. 我想将参数isLastCard传递给每张卡,以便增加列表中最后一张卡的保证金。

I have the following setup: 我有以下设置:

class CardsIndex extends StatelessWidget {

  Widget _card(context, label, bool isLastCard) {
    const double bottomMargin = isLastCard ? 40.0 : 8.0;

    return new Container(
      margin: const EdgeInsets.fromLTRB(12.0, 8.0, 12.0, bottomMargin),
      child: new Row(
          children: <Widget>[
          new Expanded(
              child: new Text(label),
          ),
          ],
      ),
    );
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
            title: new Text("Cards"),
        ),
        body: new Container(
          child: new Stack(
            children: [
              new Container(
                child: new ListView(
                  children: <Widget>[
                      _card(context, 'Card 1', false),
                      _card(context, 'Card 2', false),
                      _card(context, 'Card 3', true),
                  ],
                )
              )
            ],
          ),
        ),
    );
  }
}

This gives me this error in the output, for isLastCard inside the turnary: Const variables must be initialized with a constant value. 对于isLastCard内的isLastCard,这在输出中给了我这个错误: Const variables must be initialized with a constant value.

How do I correctly define isLastCard and bottomMargin in the _card widget? 如何在_card小部件中正确定义isLastCardbottomMargin

Thanks! 谢谢!

Figured it out. 弄清楚了。

I had to define bottomMargin as so: double bottomMargin = isLastCard ? 40.0 : 8.0; 我必须这样定义bottomMargindouble bottomMargin = isLastCard ? 40.0 : 8.0; double bottomMargin = isLastCard ? 40.0 : 8.0;

And because I was using this to set margin on the container, I had to not define margin as a const , like so: margin: EdgeInsets.fromLTRB(12.0, 8.0, 12.0, bottomMargin) 并且因为我使用它在容器上设置边距,所以不必将边距定义为const ,就像这样: margin: EdgeInsets.fromLTRB(12.0, 8.0, 12.0, bottomMargin)

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

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