简体   繁体   中英

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. Certain attributes may or may not be present in the json. For example, I receive the primaryColor but not the primarySwatch or vice versa. 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.

I am trying to avoid having to code for multiple forms of constructors based on what values are present. Note that the number of ThemeData attributes can be quite large. Here is an example with two attributes involved which results in 4 constructors.

// 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. 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. There's no difference between passing null to it or not setting it at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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