ForceDirectedGraph<T>.fromJson constructor
ForceDirectedGraph<T>.fromJson (
- String json, {
- NodeDataDeserializer<
T> ? deserializeData, - bool resetPosition = false,
- GraphConfig config = const GraphConfig(),
Create a graph from json.
resetPosition will reset the position of the nodes.
Implementation
ForceDirectedGraph.fromJson(
String json, {
NodeDataDeserializer<T>? deserializeData,
bool resetPosition = false,
this.config = const GraphConfig(),
}) {
final data = jsonDecode(json);
final nodeMap = <T, Node<T>>{};
for (final nodeData in data['nodes']) {
final actualData = deserializeData == null
? nodeData['data'] as T
: deserializeData(nodeData['data']);
final node = Node(actualData);
if (!resetPosition && nodeData['position'] != null) {
node.position =
Vector2(nodeData['position']['x'], nodeData['position']['y']);
}
nodes.add(node);
nodeMap[node.data] = node;
}
for (final edgeData in data['edges']) {
final actualDataA = deserializeData == null
? edgeData['a'] as T
: deserializeData(edgeData['a']);
final actualDataB = deserializeData == null
? edgeData['b'] as T
: deserializeData(edgeData['b']);
final a = nodeMap[actualDataA];
final b = nodeMap[actualDataB];
if (a != null && b != null) {
final edge = Edge(a, b);
edges.add(edge);
}
}
}