Reputation: 91
the idea of the code is that when the user press add, he can type a barcode or simply exit from the alert Screen. When the barcode is validated, an object is generated from this barcode, and it is added to the actual market cart. this code already works, but i am trying to find a way to somehow isolate it to a function.
IconButton(icon: Icon(Icons.add), onPressed: () {
TextEditingController barcodeController = TextEditingController();
final _formBarcode = GlobalKey<FormState>();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Stack(
overflow: Overflow.visible,
children: <Widget>[
Form(
key: _formBarcode,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: EdgeInsets.all(2.0),
child: TextFormField(
validator: (String value) {
if (BarcodeController.text.isEmpty) {
return "please enter the product barcode";
}
return null;
},
onSaved: (String value) {
},
controller: barcodeController,
style: TextStyle(
color: Colors.black,
fontSize: 10.0,
fontWeight: FontWeight.w700,
),
decoration: InputDecoration(
labelText: "barcode:",
labelStyle: new TextStyle(
fontSize: 12,
),
suffixIcon: IconButton(icon: Icon(Icons.camera_alt), onPressed: () async {}),
),
),
),
Padding(
padding: EdgeInsets.all(12),
),
Padding(
padding: const EdgeInsets.all(2.0),
child: RaisedButton(
color: Colors.black,
child: Text(
"Confirmar",
style: TextStyle(color: Colors.white),
),
onPressed: () {
if (_formBarcode.currentState.validate()) {
_formBarcode.currentState.save();
Navigator.pop(context, item("11111", BarcodeController.text));
}
},
),
)
],
),
),
],
),
);
})
.then((value) {
print(value);
if(value != null && value is item){
setState(() {
cart.add(value);
});
}
});
so it looks like
IconButton(icon: Icon(Icons.add), onPressed: () {
AddButtonAction().then((value) {
print(value);
if(value != null && value is item){
setState(() {
cart.add(value);
});
}
i have tried returns like Future but got null when did it, the function returned before i save the form, probably because of the return AlertDialog
Upvotes: 4
Views: 6042
Reputation: 7128
For a bolian result you can escape the dialog used Navigator.pop(context, true)
:
Future<bool> catLoversDialog() async {
return await showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text("Do you love cats?"),
actions: [
TextButton(
child: Text("no", style: TextStyle(color: Colors.grey)),
onPressed: () {
Navigator.pop(context, false);
}),
TextButton(
child: Text("yes!", style: TextStyle(color: Colors.blue)),
onPressed: () {
Navigator.pop(context, true);
})
],
),
);
}
use await
or then
to get the result:
result = await catLoversDialog();
Upvotes: 12
Reputation: 11984
The Future
that showDialog returns contains what you gave to Navigator.pop()
var result = await showDialog(
//Your Dialog Code that does Navigator.pop(context, result) when necessary
);
print(result); // this is the result that the dialog sent over
Upvotes: 13