Skip to content

Instantly share code, notes, and snippets.

@gausoft
Created April 6, 2023 08:17
Show Gist options
  • Save gausoft/4702f95f42639706e4d38bf765fe400d to your computer and use it in GitHub Desktop.
Save gausoft/4702f95f42639706e4d38bf765fe400d to your computer and use it in GitHub Desktop.
Ajout de produit
import 'package:flutter/material.dart';
import 'product.dart';
class AddProduct extends StatefulWidget {
const AddProduct({Key? key}) : super(key: key);
@override
_AddProductState createState() => _AddProductState();
}
class _AddProductState extends State<AddProduct> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _priceController = TextEditingController();
void _addProduct(BuildContext context) {
if (_formKey.currentState!.validate()) {
final name = _nameController.text;
final price = double.tryParse(_priceController.text) ?? 0.0;
final product = Product(name: name, price: price);
Navigator.pop(context, product);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Add a product'),
),
body: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _nameController,
decoration: InputDecoration(
labelText: 'Name',
),
validator: (value) {
if (value!.isEmpty) {
return 'Please enter a name';
}
return null;
},
),
TextFormField(
controller: _priceController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Price',
),
validator: (value) {
if (value!.isEmpty) {
return 'Please enter a price';
}
final price = double.tryParse(value);
if (price == null || price <= 0.0) {
return 'Please enter a valid price';
}
return null;
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _addProduct(context),
child: const Icon(Icons.check),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment