【问题标题】:Can I save on a variable some named arguments, in order to reuse it?我可以在变量上保存一些命名参数,以便重用它吗?
【发布时间】:2020-07-01 17:21:54
【问题描述】:

我在一些组件上有很多共同的参数,所以我想重用它们,但不需要为此创建一个新的 Widget。

例如,在 JS/React 上我们可以这样做:

const defaultProps = {
  a: 1,
  b: 2,
}

<Foo {...defaultProps} />
<Bar {...defaultProps} />
<Baz {...defaultProps} />

在 Dart/Flutter 上有类似的东西吗?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以定义一个包含所有这些属性的类,并在不同的小部件中使用该类。例如:

    class SomeClassWithProps{}
    
    class Foo extends StatelessWidget {
      final SomeClassWithProps props;
    }
    
    class Bar extends StatelessWidget {
      final SomeClassWithProps props;
    }
    
    class Baz extends StatelessWidget {
      final SomeClassWithProps props;
    }
    

    然后,当您使用这些小部件时,您可以定义一次道具并在所有这些小部件中使用它。

    【讨论】:

    • 感谢您的回答,但这并不是我想要的,因为我想要一个需要编写更少样板文件并且比包装小部件更灵活的解决方案。跨度>
    【解决方案2】:
    class YourCustomClass extends StatelessWidget {
      /// These are the arguments you want to pass in
      /// Note: The parameter can be any data type, Function or Widget
      final Color yourColor;
      final String yourText;
    
      /// This is your constructor for the class (your custom component)
      /// It basically serves as your blueprint
      /// I used the @required annotation for the first parameter to indicate that parameter must be provided
      YourCustomClass({@required this.yourColor, this.yourText});
    
      @override
      Widget build(BuildContext context) {
        return Card(
          /// The color pass in through the constructor will be used here
          color: yourColor,
    
          /// The String pass in through the constructor will be displayed here
          child: Text(yourText),
        );
      }
    }
    

    您现在可以使用这个 StatelessWidget 类并传入参数。因此您无需再次编写样板代码。将组件导入到您需要它传递参数并使用的类中。希望它有效!

    【讨论】:

    • 感谢您的回答,但这并不是我想要的,因为我想要一个需要编写更少样板的解决方案,并且更灵活地包装小部件。跨度>
    猜你喜欢
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2019-01-11
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多