Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use string instead of index for serializing constraint enum #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ private static Constraints parseConstraints(@Nullable Object json) {

if (constraintsJson.get("networkType") != null) {
builder.setRequiredNetworkType(
NetworkType.values()[(Integer) constraintsJson.get("networkType")]);
NetworkType.valueOf((String) constraintsJson.get("networkType")));
}
if (constraintsJson.get("batteryNotLow") != null) {
builder.setRequiresBatteryNotLow((Boolean) constraintsJson.get("batteryNotLow"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public void parseInvalidBackoffCriteria() {
@Test
public void parseConstraints() {
Map<String, Object> constraintsJson = new HashMap<>();
constraintsJson.put("networkType", NetworkType.NOT_ROAMING.ordinal());
constraintsJson.put("networkType", NetworkType.NOT_ROAMING.toString());
constraintsJson.put("batteryNotLow", true);
constraintsJson.put("charging", null);
constraintsJson.put("deviceIdle", true);
Expand Down
9 changes: 8 additions & 1 deletion lib/src/constraints.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class WorkConstraints {

/// Serializes this constraints into a json object.
Map<String, dynamic> toJson() => {
'networkType': networkType?.index,
'networkType': networkType == null ? null : _enumToSnakeCaseString(networkType),
'batteryNotLow': batteryNotLow,
'charging': charging,
'deviceIdle': deviceIdle,
Expand All @@ -75,3 +75,10 @@ enum NetworkType {
/// An unmetered network connection is required for this work.
unmetered,
}

String _enumToSnakeCaseString(NetworkType networkType) => networkType
.toString()
.split('.')
.last
.replaceAllMapped(RegExp(r'(?<=[a-z])[A-Z]'), (m) => ('_' + m.group(0)))
.toUpperCase();