Skip to content

Instantly share code, notes, and snippets.

@antklim
Last active November 3, 2020 05:05
Show Gist options
  • Save antklim/0145b6ee51b946e9da2f8eadfda361fe to your computer and use it in GitHub Desktop.
Save antklim/0145b6ee51b946e9da2f8eadfda361fe to your computer and use it in GitHub Desktop.
enum Operand { A, B } // Added to identify operands
class CalculatorInput extends StatefulWidget {
final num memory; // Memory state passed by parent widget
final ValueChanged<num> onChanged; // Calculator state listener
const CalculatorInput({Key key, this.memory, this.onChanged})
: super(key: key);
@override
_CalculatorInputState createState() => _CalculatorInputState();
}
class _CalculatorInputState extends State<CalculatorInput> {
...
// Added to handle operand values
num operandA = 0;
num operandB = 0;
void onOperationChanged(Operation newOperation) {
...
widget.onChanged(calculatorValue);
}
ValueChanged<String> onOperandChanged(Operand operand) => (String v) {
double value = double.tryParse(v) ?? 0;
setState(() {
if (operand == Operand.A) operandA = value;
if (operand == Operand.B) operandB = value;
});
widget.onChanged(calculatorValue);
};
num get calculatorValue {
switch (operation) {
case Operation.addition:
return operandA + operandB;
case Operation.subtraction:
return operandA - operandB;
case Operation.multiplication:
return operandA * operandB;
case Operation.division:
return operandA / operandB;
case Operation.sqrt:
return sqrt(operandA);
default:
return 0;
}
}
String get calculatorFormat {
switch (operation) {
case Operation.addition:
return '$operandA + $operandB';
case Operation.subtraction:
return '$operandA - $operandB';
case Operation.multiplication:
return '$operandA * $operandB';
case Operation.division:
return '$operandA / $operandB';
case Operation.sqrt:
return 'sqrt($operandA)';
default:
return '';
}
}
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(top: 10),
child: Column(
children: <Widget>[
...
OperandInput(
label: 'Operand A',
initValue: operandA,
memory: widget.memory,
onChanged: onOperandChanged(Operand.A)),
operation == Operation.sqrt
? SizedBox(height: 68)
: OperandInput(
label: 'Operand B',
initValue: operandB,
memory: widget.memory,
onChanged: onOperandChanged(Operand.B)),
Container(
margin: const EdgeInsets.only(top: 10, bottom: 20),
child: Text(
'$calculatorFormat = ${calculatorValue.toStringAsFixed(3)}')), // Output operation result
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment