[英]Choosing which named parameters to include in a dart class constructor at run-time
Here is a newbie question.这是一个新手问题。 I read ThemeData for a flutter app from a json file.我从 json 文件中读取了 flutter 应用程序的 ThemeData。 Certain attributes may or may not be present in the json. json 中可能存在也可能不存在某些属性。 For example, I receive the primaryColor but not the primarySwatch or vice versa.例如,我收到了 primaryColor,但没有收到 primarySwatch,反之亦然。 I would like to know if there is a simple way to instantiate the ThemeData object depending on which named parameters (corresponding to json attributes) need to be present.我想知道是否有一种简单的方法来实例化 ThemeData object,具体取决于需要存在哪些命名参数(对应于 json 属性)。
I am trying to avoid having to code for multiple forms of constructors based on what values are present.我试图避免必须根据存在的值对多个 forms 构造函数进行编码。 Note that the number of ThemeData attributes can be quite large.请注意,ThemeData 属性的数量可能非常大。 Here is an example with two attributes involved which results in 4 constructors.这是一个涉及两个属性的示例,导致 4 个构造函数。
// When no attribute is present
return ThemeData();
// When primaryColor is present
return ThemeData(
primaryColor: primaryColorFromJson,
);
// When primarySwatch is present
return ThemeData(
primarySwatch: primarySwatchFromJson,
);
// When both are present
return ThemeData(
primarySwatch: primarySwatchFromJson,
primaryColor: primaryColorFromJson,
);
It's ok if you just pass null to ThemeData constructor, in case there's no value for that in your json.如果您只是将 null 传递给ThemeData构造函数,就可以了,以防您的 json 中没有该值。 Take a look at a part of constructor:看一下构造函数的一部分:
primarySwatch ??= Colors.blue;
primaryColor ??= isDark ? Colors.grey[900] : primarySwatch;
It sets every null parameter value from constructor to default value.它将每个 null 参数值从构造函数设置为默认值。 There's no difference between passing null to it or not setting it at all.将 null 传递给它或根本不设置它没有区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.