Skip to content

Instantly share code, notes, and snippets.

@xros
Created December 18, 2021 02:18
Show Gist options
  • Save xros/17ab0ad00bf32e004e5fa86c51f636eb to your computer and use it in GitHub Desktop.
Save xros/17ab0ad00bf32e004e5fa86c51f636eb to your computer and use it in GitHub Desktop.
import 'dart:math';
/*
We can use abstract classes to define an interface that can be implemented by subclasses
Very powerful: decouples code that uses an interface from its implementation
printArea() doesn't need to know that Sqaure and Circle even exist.
only needs a Shape argument with an area property
*/
abstract class Shape {
double get area;
const Shape();
factory Shape.fromJson(Map<String, Object> json) {
final type = json['type'];
switch (type) {
case 'square':
final side = json['side'];
if (side is double) {
return Square(side);
}
throw UnsupportedError('invalid or missing side property');
case 'circle':
final radius = json['radius'];
if (radius is double) {
return Circle(radius);
}
throw UnsupportedError('invalid or missing radius property');
default:
throw UnimplementedError('invalid type $type');
}
}
}
class Square extends Shape {
const Square(this.side);
final double side;
@override
double get area => side * side;
}
class Circle extends Shape {
const Circle(this.radius);
final double radius;
@override
double get area => pi * radius * radius;
}
void printArea(Shape shape) {
print(shape.area);
}
void main() {
final shapeJson = [
{
'type': 'square',
'side': 10.0,
},
{
'type': 'circle',
'radius': 5.0,
}
];
shapeJson.forEach((element) => {printArea(Shape.fromJson(element))}); // same
// create a new Mapped List Iterable
final shapes = shapeJson.map((e) => Shape.fromJson(e)); // same
// get area for each element
shapes.forEach(printArea);
}
@xros
Copy link
Author

xros commented Dec 18, 2021

output is

100.0
78.53981633974483
100.0
78.53981633974483

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment