Skip to content

Instantly share code, notes, and snippets.

@stegrams
Last active June 2, 2020 01:30
Show Gist options
  • Save stegrams/275d0bdd50026c5643d2faa77b49f701 to your computer and use it in GitHub Desktop.
Save stegrams/275d0bdd50026c5643d2faa77b49f701 to your computer and use it in GitHub Desktop.
A form field that it's value is calculated based on the values of two others.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _amount = '0';
var _assetQtyControler = TextEditingController(text: '0');
var _unitCostControler = TextEditingController(text: '0');
var _amountControler = TextEditingController();
void _updateAmount(_) {
double dQty = double.tryParse(_assetQtyControler.text);
double dCost = dQty == null
? null
: double.tryParse(
_unitCostControler.text,
);
String amount;
if (dCost == null)
amount = '0';
else
amount = (dQty * dCost).toString();
setState(() => _amount = amount);
}
@override
void dispose() {
_assetQtyControler.dispose();
_unitCostControler.dispose();
_amountControler.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
_amountControler.text = _amount;
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
TextFormField(
controller: _assetQtyControler,
keyboardType: TextInputType.number,
decoration: InputDecoration(labelText: 'Asset Quantity'),
onChanged: _updateAmount,
),
SizedBox(height: 20),
TextFormField(
controller: _unitCostControler,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Unit Cost',
prefixText: 'Shs.',
),
onChanged: _updateAmount,
),
SizedBox(height: 20),
TextFormField(
controller: _amountControler,
decoration: InputDecoration(
labelText: 'Amount',
prefixText: 'Shs.',
),
enabled: false,
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment