From 807a9b80a46e4738cd2f3dcff6297030bae38216 Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Fri, 14 Oct 2022 10:45:09 +0200 Subject: [PATCH 01/10] Basic layout --- lib/flutter_address_form.dart | 6 +--- lib/src/address_form.dart | 67 +++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 5 deletions(-) create mode 100644 lib/src/address_form.dart diff --git a/lib/flutter_address_form.dart b/lib/flutter_address_form.dart index 2ed7aa0..253c382 100644 --- a/lib/flutter_address_form.dart +++ b/lib/flutter_address_form.dart @@ -1,7 +1,3 @@ library flutter_address_form; -/// A Calculator. -class Calculator { - /// Returns [value] plus 1. - int addOne(int value) => value + 1; -} +export 'src/address_form.dart'; diff --git a/lib/src/address_form.dart b/lib/src/address_form.dart new file mode 100644 index 0000000..6ca5fee --- /dev/null +++ b/lib/src/address_form.dart @@ -0,0 +1,67 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; + +class AddressForm extends StatefulWidget { + AddressForm({Key? key}) : super(key: key); + + @override + State createState() => _AddressFormState(); +} + +class _AddressFormState extends State { + final TextEditingController _zipcodeController = TextEditingController(); + final RegExp _zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); + @override + Widget build(BuildContext context) { + return Form( + child: Column( + children: [ + _createField( + label: 'Postcode', + controller: _zipcodeController, + ), + Flexible( + child: Row( + children: [ + _createField( + label: 'Huisnummer', + controller: TextEditingController(), + ), + _createField( + label: 'Toevoeging', + controller: TextEditingController(), + ), + ], + ), + ), + _createField( + label: 'Straatnaam', + controller: TextEditingController(), + ), + _createField( + label: 'Woonplaats', + controller: TextEditingController(), + ) + ], + ), + ); + } + + Widget _createField( + {required String label, required TextEditingController controller}) { + return Flexible( + child: Container( + margin: const EdgeInsets.all(10), + child: TextFormField( + validator: (value) { + print(_zipcodeRegExp.hasMatch(value!)); + }, + decoration: InputDecoration( + label: Text(label), + border: const OutlineInputBorder(), + ), + ), + ), + ); + } +} From 9b7cbf4d69148c89226ac92df92f176f4df27aea Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Fri, 14 Oct 2022 10:52:33 +0200 Subject: [PATCH 02/10] fiexed example to it uses the AddressForm --- example/lib/main.dart | 84 ++++--------------------------------------- example/pubspec.lock | 8 +++++ example/pubspec.yaml | 3 ++ 3 files changed, 17 insertions(+), 78 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index e016029..6dbfa57 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter_address_form/flutter_address_form.dart'; void main() { runApp(const MyApp()); @@ -24,92 +25,19 @@ class MyApp extends StatelessWidget { // is not restarted. primarySwatch: Colors.blue, ), - home: const MyHomePage(title: 'Flutter Demo Home Page'), + home: const AddressFormExample(), ); } } -class MyHomePage extends StatefulWidget { - const MyHomePage({super.key, required this.title}); - - // This widget is the home page of your application. It is stateful, meaning - // that it has a State object (defined below) that contains fields that affect - // how it looks. - - // This class is the configuration for the state. It holds the values (in this - // case the title) provided by the parent (in this case the App widget) and - // used by the build method of the State. Fields in a Widget subclass are - // always marked "final". - - final String title; - - @override - State createState() => _MyHomePageState(); -} - -class _MyHomePageState extends State { - int _counter = 0; - - void _incrementCounter() { - setState(() { - // This call to setState tells the Flutter framework that something has - // changed in this State, which causes it to rerun the build method below - // so that the display can reflect the updated values. If we changed - // _counter without calling setState(), then the build method would not be - // called again, and so nothing would appear to happen. - _counter++; - }); - } +class AddressFormExample extends StatelessWidget { + const AddressFormExample({Key? key}) : super(key: key); @override Widget build(BuildContext context) { - // This method is rerun every time setState is called, for instance as done - // by the _incrementCounter method above. - // - // The Flutter framework has been optimized to make rerunning build methods - // fast, so that you can just rebuild anything that needs updating rather - // than having to individually change instances of widgets. return Scaffold( - appBar: AppBar( - // Here we take the value from the MyHomePage object that was created by - // the App.build method, and use it to set our appbar title. - title: Text(widget.title), - ), - body: Center( - // Center is a layout widget. It takes a single child and positions it - // in the middle of the parent. - child: Column( - // Column is also a layout widget. It takes a list of children and - // arranges them vertically. By default, it sizes itself to fit its - // children horizontally, and tries to be as tall as its parent. - // - // Invoke "debug painting" (press "p" in the console, choose the - // "Toggle Debug Paint" action from the Flutter Inspector in Android - // Studio, or the "Toggle Debug Paint" command in Visual Studio Code) - // to see the wireframe for each widget. - // - // Column has various properties to control how it sizes itself and - // how it positions its children. Here we use mainAxisAlignment to - // center the children vertically; the main axis here is the vertical - // axis because Columns are vertical (the cross axis would be - // horizontal). - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text( - 'You have pushed the button this many times:', - ), - Text( - '$_counter', - style: Theme.of(context).textTheme.headline4, - ), - ], - ), - ), - floatingActionButton: FloatingActionButton( - onPressed: _incrementCounter, - tooltip: 'Increment', - child: const Icon(Icons.add), - ), // This trailing comma makes auto-formatting nicer for build methods. + appBar: AppBar(), + body: AddressForm(), ); } } diff --git a/example/pubspec.lock b/example/pubspec.lock index 9295504..87ee284 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -55,6 +55,13 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_address_form: + dependency: "direct main" + description: + path: ".." + relative: true + source: path + version: "0.0.1" flutter_lints: dependency: "direct dev" description: @@ -158,3 +165,4 @@ packages: version: "2.1.2" sdks: dart: ">=2.18.2 <3.0.0" + flutter: ">=1.17.0" diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 8adb14e..587bd88 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -32,6 +32,9 @@ dependencies: flutter: sdk: flutter + flutter_address_form: + path: ../ + # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. From 38b0e0801c6e360fde6b7ab8262377a5d754e6ea Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Fri, 14 Oct 2022 15:32:08 +0200 Subject: [PATCH 03/10] Added simple validators --- lib/src/address_controller.dart | 13 +++ lib/src/address_form.dart | 184 +++++++++++++++++++++++--------- lib/src/models/address.dart | 30 ++++++ 3 files changed, 179 insertions(+), 48 deletions(-) create mode 100644 lib/src/address_controller.dart create mode 100644 lib/src/models/address.dart diff --git a/lib/src/address_controller.dart b/lib/src/address_controller.dart new file mode 100644 index 0000000..34d5b32 --- /dev/null +++ b/lib/src/address_controller.dart @@ -0,0 +1,13 @@ +import 'package:flutter/foundation.dart'; + +class AddressController extends ChangeNotifier { + final String zipcode; + final int houseNumber; + final String prefix; + final String street; + final String city; + + AddressController(this.zipcode, this.houseNumber, this.prefix, this.street, this.city); + + +} diff --git a/lib/src/address_form.dart b/lib/src/address_form.dart index 6ca5fee..47b6d3e 100644 --- a/lib/src/address_form.dart +++ b/lib/src/address_form.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; +import 'package:flutter_address_form/src/models/address.dart'; class AddressForm extends StatefulWidget { - AddressForm({Key? key}) : super(key: key); + const AddressForm({Key? key}) : super(key: key); @override State createState() => _AddressFormState(); @@ -10,58 +10,146 @@ class AddressForm extends StatefulWidget { class _AddressFormState extends State { final TextEditingController _zipcodeController = TextEditingController(); + final TextEditingController _houseNumberController = TextEditingController(); + final TextEditingController _prefixController = TextEditingController(); + final TextEditingController _streetController = TextEditingController(); + final TextEditingController _cityController = TextEditingController(); + final RegExp _zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); @override Widget build(BuildContext context) { - return Form( - child: Column( - children: [ - _createField( - label: 'Postcode', - controller: _zipcodeController, + return Column( + children: [ + AddressFormTextField( + controller: _zipcodeController, + validator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (!_zipcodeRegExp.hasMatch(text)) { + return 'Invalid zipcode'; + } + return null; + }, + label: 'Postcode', + ), + Flexible( + child: Row( + children: [ + AddressFormTextField( + controller: _houseNumberController, + validator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (text.length >= 3 || int.tryParse(text) == null) { + return 'Invalid number'; + } + return null; + }, + label: 'Huisnummer', + ), + AddressFormTextField( + controller: _prefixController, + validator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (RegExp(r'/^[a-z]*$/').hasMatch(text) && + text.length != 1) { + return 'Invalid prefix'; + } + return null; + }, + label: 'Toevoeging', + ), + ], ), - Flexible( - child: Row( - children: [ - _createField( - label: 'Huisnummer', - controller: TextEditingController(), - ), - _createField( - label: 'Toevoeging', - controller: TextEditingController(), - ), - ], - ), - ), - _createField( - label: 'Straatnaam', - controller: TextEditingController(), - ), - _createField( - label: 'Woonplaats', - controller: TextEditingController(), - ) - ], - ), + ), + AddressFormTextField( + controller: _streetController, + validator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + label: 'Straatnaam', + ), + AddressFormTextField( + controller: _cityController, + validator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + label: 'Woonplaats', + ), + TextButton( + onPressed: () {}, + child: Text('Test'), + ) + ], ); } - Widget _createField( - {required String label, required TextEditingController controller}) { - return Flexible( - child: Container( - margin: const EdgeInsets.all(10), - child: TextFormField( - validator: (value) { - print(_zipcodeRegExp.hasMatch(value!)); - }, - decoration: InputDecoration( - label: Text(label), - border: const OutlineInputBorder(), - ), - ), - ), - ); + @override + void dispose() { + _zipcodeController.dispose(); + _houseNumberController.dispose(); + _prefixController.dispose(); + _streetController.dispose(); + _cityController.dispose(); + super.dispose(); + } +} + +class AddressFormTextField extends StatefulWidget { + final String label; + final TextEditingController controller; + final String? Function(String) validator; + AddressFormTextField({ + Key? key, + required this.label, + required this.controller, + required this.validator, + }) : super(key: key); + + @override + State createState() => _AddressFormTextFieldState(); +} + +class _AddressFormTextFieldState extends State { + final Address addressModel = Address(); + + String? get _errorText { + final text = widget.controller.value.text; + return widget.validator(text); + } + + @override + void initState() { + super.initState(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: widget.controller, + builder: (context, value, _) { + return Flexible( + child: Container( + margin: const EdgeInsets.all(10), + child: TextField( + controller: widget.controller, + decoration: InputDecoration( + label: Text(widget.label), + border: const OutlineInputBorder(), + errorText: _errorText), + ), + ), + ); + }); } } diff --git a/lib/src/models/address.dart b/lib/src/models/address.dart new file mode 100644 index 0000000..2a6ac9f --- /dev/null +++ b/lib/src/models/address.dart @@ -0,0 +1,30 @@ +class Address { + Address({ + this.zipcode, + this.street, + this.housenumber, + this.suffix, + this.city, + }); + + final String? zipcode; + final String? street; + final int? housenumber; + final String? suffix; + final String? city; + + Address copyWith({ + String? zipcode, + String? street, + int? housenumber, + String? suffix, + String? city, + }) => + Address( + zipcode: zipcode ?? this.zipcode, + street: street ?? this.street, + housenumber: housenumber ?? this.housenumber, + suffix: suffix ?? this.suffix, + city: city ?? this.city, + ); +} From e00b961414ae1ad8ef80136d8cc6a617c42c03a0 Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Tue, 18 Oct 2022 10:14:58 +0200 Subject: [PATCH 04/10] Changes to controller --- lib/src/address_controller.dart | 41 +++++++++++++++++++++++----- lib/src/address_form.dart | 48 ++++++++++++++++----------------- lib/src/models/address.dart | 5 +++- 3 files changed, 61 insertions(+), 33 deletions(-) diff --git a/lib/src/address_controller.dart b/lib/src/address_controller.dart index 34d5b32..bdf85bb 100644 --- a/lib/src/address_controller.dart +++ b/lib/src/address_controller.dart @@ -1,13 +1,40 @@ import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_address_form/src/models/address.dart'; class AddressController extends ChangeNotifier { - final String zipcode; - final int houseNumber; - final String prefix; - final String street; - final String city; + Address address = const Address(); - AddressController(this.zipcode, this.houseNumber, this.prefix, this.street, this.city); + final TextEditingController zipcode = TextEditingController(); + final TextEditingController houseNumber = TextEditingController(); + final TextEditingController suffix = TextEditingController(); + final TextEditingController street = TextEditingController(); + final TextEditingController city = TextEditingController(); - + final Function()? onChangeInputCallback; + + AddressController(this.onChangeInputCallback); + + Address get getAddress => address; + + void setAddress( + String zipcode, + String street, + int housenumber, + String suffix, + String city, + ) { + address = address.copyWith( + zipcode: zipcode, + street: street, + housenumber: housenumber, + suffix: suffix, + city: city, + ); + notifyListeners(); + } + + void onChangeInput() { + onChangeInputCallback?.call(); + } } diff --git a/lib/src/address_form.dart b/lib/src/address_form.dart index 47b6d3e..bf3a616 100644 --- a/lib/src/address_form.dart +++ b/lib/src/address_form.dart @@ -1,4 +1,6 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_address_form/src/address_controller.dart'; import 'package:flutter_address_form/src/models/address.dart'; class AddressForm extends StatefulWidget { @@ -9,19 +11,22 @@ class AddressForm extends StatefulWidget { } class _AddressFormState extends State { - final TextEditingController _zipcodeController = TextEditingController(); - final TextEditingController _houseNumberController = TextEditingController(); - final TextEditingController _prefixController = TextEditingController(); - final TextEditingController _streetController = TextEditingController(); - final TextEditingController _cityController = TextEditingController(); + final AddressController _addressController = AddressController(() {}); final RegExp _zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); + + @override + void initState() { + _addressController; + super.initState(); + } + @override Widget build(BuildContext context) { return Column( children: [ AddressFormTextField( - controller: _zipcodeController, + controller: _addressController.zipcode, validator: (text) { if (text.isEmpty) { return 'Can\'t be empty'; @@ -31,13 +36,13 @@ class _AddressFormState extends State { } return null; }, - label: 'Postcode', + label: const Text('Postcode'), ), Flexible( child: Row( children: [ AddressFormTextField( - controller: _houseNumberController, + controller: _addressController.houseNumber, validator: (text) { if (text.isEmpty) { return 'Can\'t be empty'; @@ -47,10 +52,10 @@ class _AddressFormState extends State { } return null; }, - label: 'Huisnummer', + label: const Text('Huisnummer'), ), AddressFormTextField( - controller: _prefixController, + controller: _addressController.suffix, validator: (text) { if (text.isEmpty) { return 'Can\'t be empty'; @@ -61,30 +66,30 @@ class _AddressFormState extends State { } return null; }, - label: 'Toevoeging', + label: const Text('Toevoeging'), ), ], ), ), AddressFormTextField( - controller: _streetController, + controller: _addressController.street, validator: (text) { if (text.isEmpty) { return 'Can\'t be empty'; } return null; }, - label: 'Straatnaam', + label: const Text('Straatnaam'), ), AddressFormTextField( - controller: _cityController, + controller: _addressController.city, validator: (text) { if (text.isEmpty) { return 'Can\'t be empty'; } return null; }, - label: 'Woonplaats', + label: const Text('Woonplaats'), ), TextButton( onPressed: () {}, @@ -96,20 +101,15 @@ class _AddressFormState extends State { @override void dispose() { - _zipcodeController.dispose(); - _houseNumberController.dispose(); - _prefixController.dispose(); - _streetController.dispose(); - _cityController.dispose(); super.dispose(); } } class AddressFormTextField extends StatefulWidget { - final String label; + final Widget label; final TextEditingController controller; final String? Function(String) validator; - AddressFormTextField({ + const AddressFormTextField({ Key? key, required this.label, required this.controller, @@ -121,8 +121,6 @@ class AddressFormTextField extends StatefulWidget { } class _AddressFormTextFieldState extends State { - final Address addressModel = Address(); - String? get _errorText { final text = widget.controller.value.text; return widget.validator(text); @@ -144,7 +142,7 @@ class _AddressFormTextFieldState extends State { child: TextField( controller: widget.controller, decoration: InputDecoration( - label: Text(widget.label), + label: widget.label, border: const OutlineInputBorder(), errorText: _errorText), ), diff --git a/lib/src/models/address.dart b/lib/src/models/address.dart index 2a6ac9f..8e4d876 100644 --- a/lib/src/models/address.dart +++ b/lib/src/models/address.dart @@ -1,5 +1,8 @@ +import 'package:flutter/material.dart' show immutable; + +@immutable class Address { - Address({ + const Address({ this.zipcode, this.street, this.housenumber, From 1107729c793382c0b8f14a9e5de2afa5cd8cf9f3 Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Wed, 19 Oct 2022 11:52:57 +0200 Subject: [PATCH 05/10] Functionally working Adressform --- example/lib/main.dart | 48 +++- lib/src/address_controller.dart | 40 ---- lib/src/address_form.dart | 223 ++++++++++-------- .../{address.dart => address_model.dart} | 8 +- test/flutter_address_form_test.dart | 57 ++++- 5 files changed, 229 insertions(+), 147 deletions(-) delete mode 100644 lib/src/address_controller.dart rename lib/src/models/{address.dart => address_model.dart} (87%) diff --git a/example/lib/main.dart b/example/lib/main.dart index 6dbfa57..c6bd1e6 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -25,19 +25,61 @@ class MyApp extends StatelessWidget { // is not restarted. primarySwatch: Colors.blue, ), - home: const AddressFormExample(), + home: AddressFormExample(), ); } } class AddressFormExample extends StatelessWidget { - const AddressFormExample({Key? key}) : super(key: key); + AddressFormExample({Key? key}) : super(key: key); + + final RegExp zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), - body: AddressForm(), + body: AddressForm( + zipCodeValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (!zipcodeRegExp.hasMatch(text)) { + return 'Invalid zipcode'; + } + return null; + }, + housenumberValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (text.length >= 3 || int.tryParse(text) == null) { + return 'Invalid number'; + } + return null; + }, + suffixValidator: (text) { + if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { + return 'Invalid prefix'; + } + return null; + }, + streetValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + cityValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + controller: AddressController(onAutoComplete: (address) { + return address; + }), + ), ); } } diff --git a/lib/src/address_controller.dart b/lib/src/address_controller.dart deleted file mode 100644 index bdf85bb..0000000 --- a/lib/src/address_controller.dart +++ /dev/null @@ -1,40 +0,0 @@ -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_address_form/src/models/address.dart'; - -class AddressController extends ChangeNotifier { - Address address = const Address(); - - final TextEditingController zipcode = TextEditingController(); - final TextEditingController houseNumber = TextEditingController(); - final TextEditingController suffix = TextEditingController(); - final TextEditingController street = TextEditingController(); - final TextEditingController city = TextEditingController(); - - final Function()? onChangeInputCallback; - - AddressController(this.onChangeInputCallback); - - Address get getAddress => address; - - void setAddress( - String zipcode, - String street, - int housenumber, - String suffix, - String city, - ) { - address = address.copyWith( - zipcode: zipcode, - street: street, - housenumber: housenumber, - suffix: suffix, - city: city, - ); - notifyListeners(); - } - - void onChangeInput() { - onChangeInputCallback?.call(); - } -} diff --git a/lib/src/address_form.dart b/lib/src/address_form.dart index bf3a616..988bad7 100644 --- a/lib/src/address_form.dart +++ b/lib/src/address_form.dart @@ -1,111 +1,83 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_address_form/src/address_controller.dart'; -import 'package:flutter_address_form/src/models/address.dart'; -class AddressForm extends StatefulWidget { - const AddressForm({Key? key}) : super(key: key); +import 'package:flutter_address_form/src/models/address_model.dart'; - @override - State createState() => _AddressFormState(); -} - -class _AddressFormState extends State { - final AddressController _addressController = AddressController(() {}); - - final RegExp _zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); - - @override - void initState() { - _addressController; - super.initState(); +class AddressForm extends StatelessWidget { + AddressForm({ + Key? key, + this.zipCodeLabel = const Text('Zipcode'), + this.housenumberLabel = const Text('Housenumber'), + this.suffixLabel = const Text('Suffix'), + this.streetLabel = const Text('Street'), + this.cityLabel = const Text('City'), + required this.zipCodeValidator, + required this.housenumberValidator, + required this.suffixValidator, + required this.streetValidator, + required this.cityValidator, + AddressController? controller, + }) { + _addressController = + controller ?? AddressController(onAutoComplete: (model) => model); } + final Widget zipCodeLabel; + final Widget housenumberLabel; + final Widget suffixLabel; + final Widget streetLabel; + final Widget cityLabel; + + final String? Function(String) zipCodeValidator; + final String? Function(String) housenumberValidator; + final String? Function(String) suffixValidator; + final String? Function(String) streetValidator; + final String? Function(String) cityValidator; + + late final AddressController _addressController; + @override Widget build(BuildContext context) { return Column( children: [ AddressFormTextField( - controller: _addressController.zipcode, - validator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (!_zipcodeRegExp.hasMatch(text)) { - return 'Invalid zipcode'; - } - return null; - }, - label: const Text('Postcode'), + controller: _addressController._zipcodeController, + validator: zipCodeValidator, + label: zipCodeLabel, ), Flexible( child: Row( children: [ AddressFormTextField( - controller: _addressController.houseNumber, - validator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (text.length >= 3 || int.tryParse(text) == null) { - return 'Invalid number'; - } - return null; - }, - label: const Text('Huisnummer'), + controller: _addressController._housenumberController, + validator: housenumberValidator, + label: housenumberLabel, ), AddressFormTextField( - controller: _addressController.suffix, - validator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (RegExp(r'/^[a-z]*$/').hasMatch(text) && - text.length != 1) { - return 'Invalid prefix'; - } - return null; - }, - label: const Text('Toevoeging'), + controller: _addressController._suffixController, + validator: suffixValidator, + label: suffixLabel, ), ], ), ), AddressFormTextField( - controller: _addressController.street, - validator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - return null; - }, - label: const Text('Straatnaam'), + controller: _addressController._streetController, + validator: streetValidator, + label: streetLabel, ), AddressFormTextField( - controller: _addressController.city, - validator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - return null; - }, - label: const Text('Woonplaats'), + controller: _addressController._cityController, + validator: cityValidator, + label: cityLabel, ), - TextButton( - onPressed: () {}, - child: Text('Test'), - ) ], ); } - - @override - void dispose() { - super.dispose(); - } } -class AddressFormTextField extends StatefulWidget { +class AddressFormTextField extends StatelessWidget { final Widget label; final TextEditingController controller; final String? Function(String) validator; @@ -116,33 +88,20 @@ class AddressFormTextField extends StatefulWidget { required this.validator, }) : super(key: key); - @override - State createState() => _AddressFormTextFieldState(); -} - -class _AddressFormTextFieldState extends State { - String? get _errorText { - final text = widget.controller.value.text; - return widget.validator(text); - } - - @override - void initState() { - super.initState(); - } + String? get _errorText => validator(controller.value.text); @override Widget build(BuildContext context) { return ValueListenableBuilder( - valueListenable: widget.controller, + valueListenable: controller, builder: (context, value, _) { return Flexible( child: Container( margin: const EdgeInsets.all(10), child: TextField( - controller: widget.controller, + controller: controller, decoration: InputDecoration( - label: widget.label, + label: label, border: const OutlineInputBorder(), errorText: _errorText), ), @@ -151,3 +110,77 @@ class _AddressFormTextFieldState extends State { }); } } + +class AddressController extends ChangeNotifier { + final AddressModel? initialValue; + final FutureOr Function(AddressModel)? onAutoComplete; + + AddressController({this.initialValue, this.onAutoComplete}) { + _model = initialValue ?? + const AddressModel( + zipcode: null, + street: null, + housenumber: null, + suffix: null, + city: null, + ); + + _zipcodeController.addListener(_update); + _streetController.addListener(_update); + _housenumberController.addListener(_update); + _suffixController.addListener(_update); + _cityController.addListener(_update); + } + + late AddressModel _model; + + late final _zipcodeController = + TextEditingController(text: initialValue?.zipcode); + late final _streetController = + TextEditingController(text: initialValue?.street); + late final _housenumberController = + TextEditingController(text: initialValue?.housenumber.toString()); + late final _suffixController = + TextEditingController(text: initialValue?.suffix); + late final _cityController = TextEditingController(text: initialValue?.city); + + AddressModel get model => _model; + + void _update() async { + AddressModel updatedModel = _model.copyWith( + zipcode: _zipcodeController.text, + street: _streetController.text, + housenumber: int.tryParse(_housenumberController.text), + suffix: _suffixController.text, + city: _cityController.text); + _model = await onAutoComplete?.call(updatedModel) ?? updatedModel; + + if (_model.zipcode != updatedModel.zipcode) { + _zipcodeController.text = _model.zipcode ?? ''; + } + if (_model.street != updatedModel.street) { + _streetController.text = _model.street ?? ''; + } + if (_model.housenumber != updatedModel.housenumber) { + _housenumberController.text = _model.housenumber?.toString() ?? ''; + } + if (_model.suffix != updatedModel.suffix) { + _suffixController.text = _model.suffix ?? ''; + } + if (_model.city != updatedModel.city) { + _cityController.text = _model.city ?? ''; + } + + notifyListeners(); + } + + @override + void dispose() { + super.dispose(); + _zipcodeController.dispose(); + _streetController.dispose(); + _housenumberController.dispose(); + _suffixController.dispose(); + _cityController.dispose(); + } +} diff --git a/lib/src/models/address.dart b/lib/src/models/address_model.dart similarity index 87% rename from lib/src/models/address.dart rename to lib/src/models/address_model.dart index 8e4d876..51e52b4 100644 --- a/lib/src/models/address.dart +++ b/lib/src/models/address_model.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart' show immutable; @immutable -class Address { - const Address({ +class AddressModel { + const AddressModel({ this.zipcode, this.street, this.housenumber, @@ -16,14 +16,14 @@ class Address { final String? suffix; final String? city; - Address copyWith({ + AddressModel copyWith({ String? zipcode, String? street, int? housenumber, String? suffix, String? city, }) => - Address( + AddressModel( zipcode: zipcode ?? this.zipcode, street: street ?? this.street, housenumber: housenumber ?? this.housenumber, diff --git a/test/flutter_address_form_test.dart b/test/flutter_address_form_test.dart index 2fc3dc0..56106d7 100644 --- a/test/flutter_address_form_test.dart +++ b/test/flutter_address_form_test.dart @@ -1,12 +1,59 @@ +import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_address_form/flutter_address_form.dart'; void main() { - test('adds one to input values', () { - final calculator = Calculator(); - expect(calculator.addOne(2), 3); - expect(calculator.addOne(-7), -6); - expect(calculator.addOne(0), 1); + testWidgets('Render App with AddressForm Widget', (tester) async { + final RegExp zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + appBar: AppBar(), + body: AddressForm( + zipCodeValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (!zipcodeRegExp.hasMatch(text)) { + return 'Invalid zipcode'; + } + return null; + }, + housenumberValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (text.length >= 3 || int.tryParse(text) == null) { + return 'Invalid number'; + } + return null; + }, + suffixValidator: (text) { + if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { + return 'Invalid prefix'; + } + return null; + }, + streetValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + cityValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + controller: AddressController(onAutoComplete: (address) { + return address; + }), + ), + ), + ), + ); + await tester.pump(); }); } From 1b4d9205865aed1ef5dc119826fbf56152e11853 Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Wed, 19 Oct 2022 12:38:08 +0200 Subject: [PATCH 06/10] changed housenumber to String --- lib/src/address_form.dart | 12 +++++++++--- lib/src/models/address_model.dart | 4 ++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/lib/src/address_form.dart b/lib/src/address_form.dart index 988bad7..c07b805 100644 --- a/lib/src/address_form.dart +++ b/lib/src/address_form.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_address_form/src/models/address_model.dart'; +/// A widget that creates a form with different address fields widgets. +/// Returns a `AddressModel` Object from a `AddressController`. class AddressForm extends StatelessWidget { AddressForm({ Key? key, @@ -35,6 +37,7 @@ class AddressForm extends StatelessWidget { final String? Function(String) streetValidator; final String? Function(String) cityValidator; + /// Controls the `AddressModel` late final AddressController _addressController; @override @@ -112,7 +115,10 @@ class AddressFormTextField extends StatelessWidget { } class AddressController extends ChangeNotifier { + /// An optional value to initialize the form field to, or null otherwise. final AddressModel? initialValue; + + /// When the form changes, the function passes the current `AddressModel` as an argument and gives the possibility to manipulate and return a `AddressModel`. final FutureOr Function(AddressModel)? onAutoComplete; AddressController({this.initialValue, this.onAutoComplete}) { @@ -139,7 +145,7 @@ class AddressController extends ChangeNotifier { late final _streetController = TextEditingController(text: initialValue?.street); late final _housenumberController = - TextEditingController(text: initialValue?.housenumber.toString()); + TextEditingController(text: initialValue?.housenumber); late final _suffixController = TextEditingController(text: initialValue?.suffix); late final _cityController = TextEditingController(text: initialValue?.city); @@ -150,7 +156,7 @@ class AddressController extends ChangeNotifier { AddressModel updatedModel = _model.copyWith( zipcode: _zipcodeController.text, street: _streetController.text, - housenumber: int.tryParse(_housenumberController.text), + housenumber: _housenumberController.text, suffix: _suffixController.text, city: _cityController.text); _model = await onAutoComplete?.call(updatedModel) ?? updatedModel; @@ -162,7 +168,7 @@ class AddressController extends ChangeNotifier { _streetController.text = _model.street ?? ''; } if (_model.housenumber != updatedModel.housenumber) { - _housenumberController.text = _model.housenumber?.toString() ?? ''; + _housenumberController.text = _model.housenumber ?? ''; } if (_model.suffix != updatedModel.suffix) { _suffixController.text = _model.suffix ?? ''; diff --git a/lib/src/models/address_model.dart b/lib/src/models/address_model.dart index 51e52b4..7e060c7 100644 --- a/lib/src/models/address_model.dart +++ b/lib/src/models/address_model.dart @@ -12,14 +12,14 @@ class AddressModel { final String? zipcode; final String? street; - final int? housenumber; + final String? housenumber; final String? suffix; final String? city; AddressModel copyWith({ String? zipcode, String? street, - int? housenumber, + String? housenumber, String? suffix, String? city, }) => From affa510a5c51993283f6271a2ed67ec2b7893e21 Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Tue, 25 Oct 2022 08:36:32 +0200 Subject: [PATCH 07/10] WIP adresscontroller validator --- example/lib/main.dart | 96 +++++++++-------- lib/flutter_address_form.dart | 1 + lib/src/address_form.dart | 153 ++++++++++++++++------------ pubspec.yaml | 1 - test/flutter_address_form_test.dart | 81 ++++++++------- 5 files changed, 187 insertions(+), 145 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index c6bd1e6..9d712df 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -31,54 +31,66 @@ class MyApp extends StatelessWidget { } class AddressFormExample extends StatelessWidget { - AddressFormExample({Key? key}) : super(key: key); + AddressFormExample({super.key}); - final RegExp zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); + // final RegExp zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); + + final _addressController = AddressController( + zipCodeValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (!RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$').hasMatch(text)) { + return 'Invalid zipcode'; + } + return null; + }, + housenumberValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (text.length >= 3 || int.tryParse(text) == null) { + return 'Invalid number'; + } + return null; + }, + suffixValidator: (text) { + if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { + return 'Invalid prefix'; + } + return null; + }, + streetValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + onAutoComplete: (address) { + return address; + }, + cityValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + ); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), - body: AddressForm( - zipCodeValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (!zipcodeRegExp.hasMatch(text)) { - return 'Invalid zipcode'; - } - return null; - }, - housenumberValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (text.length >= 3 || int.tryParse(text) == null) { - return 'Invalid number'; - } - return null; - }, - suffixValidator: (text) { - if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { - return 'Invalid prefix'; - } - return null; - }, - streetValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - return null; - }, - cityValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - return null; - }, - controller: AddressController(onAutoComplete: (address) { - return address; - }), + body: Column( + children: [ + AddressForm( + onSubmit: (value) => value, controller: _addressController), + TextButton( + onPressed: () { + _addressController.validate; + }, + child: Text('Test')) + ], ), ); } diff --git a/lib/flutter_address_form.dart b/lib/flutter_address_form.dart index 253c382..8ae6d3d 100644 --- a/lib/flutter_address_form.dart +++ b/lib/flutter_address_form.dart @@ -1,3 +1,4 @@ library flutter_address_form; export 'src/address_form.dart'; +export 'src/models/address_model.dart'; diff --git a/lib/src/address_form.dart b/lib/src/address_form.dart index c07b805..3493112 100644 --- a/lib/src/address_form.dart +++ b/lib/src/address_form.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:ffi'; import 'package:flutter/material.dart'; @@ -6,74 +7,74 @@ import 'package:flutter_address_form/src/models/address_model.dart'; /// A widget that creates a form with different address fields widgets. /// Returns a `AddressModel` Object from a `AddressController`. -class AddressForm extends StatelessWidget { +class AddressForm extends StatefulWidget { AddressForm({ - Key? key, - this.zipCodeLabel = const Text('Zipcode'), - this.housenumberLabel = const Text('Housenumber'), - this.suffixLabel = const Text('Suffix'), - this.streetLabel = const Text('Street'), - this.cityLabel = const Text('City'), - required this.zipCodeValidator, - required this.housenumberValidator, - required this.suffixValidator, - required this.streetValidator, - required this.cityValidator, + super.key, AddressController? controller, + this.zipCodeDecoration = const InputDecoration(label: Text('Zipcode')), + this.housenumberDecoration = + const InputDecoration(label: Text('Housenumber')), + this.suffixDecoration = const InputDecoration(label: Text('Suffix')), + this.streetDecoration = const InputDecoration(label: Text('Street')), + this.cityDecoration = const InputDecoration(label: Text('City')), + required this.onSubmit, }) { - _addressController = - controller ?? AddressController(onAutoComplete: (model) => model); + _addressController = controller ?? + AddressController( + onAutoComplete: (model) => model, + zipCodeValidator: (text) => null, + cityValidator: (text) => null, + housenumberValidator: (text) => null, + streetValidator: (text) => null, + suffixValidator: (text) => null, + ); } - final Widget zipCodeLabel; - final Widget housenumberLabel; - final Widget suffixLabel; - final Widget streetLabel; - final Widget cityLabel; + final InputDecoration zipCodeDecoration; + final InputDecoration housenumberDecoration; + final InputDecoration suffixDecoration; + final InputDecoration streetDecoration; + final InputDecoration cityDecoration; - final String? Function(String) zipCodeValidator; - final String? Function(String) housenumberValidator; - final String? Function(String) suffixValidator; - final String? Function(String) streetValidator; - final String? Function(String) cityValidator; + final ValueChanged onSubmit; /// Controls the `AddressModel` late final AddressController _addressController; + @override + State createState() => _AddressFormState(); +} + +class _AddressFormState extends State { @override Widget build(BuildContext context) { return Column( children: [ AddressFormTextField( - controller: _addressController._zipcodeController, - validator: zipCodeValidator, - label: zipCodeLabel, + controller: widget._addressController._zipcodeController, + fieldDecoration: widget.zipCodeDecoration, ), Flexible( child: Row( children: [ AddressFormTextField( - controller: _addressController._housenumberController, - validator: housenumberValidator, - label: housenumberLabel, + controller: widget._addressController._housenumberController, + fieldDecoration: widget.housenumberDecoration, ), AddressFormTextField( - controller: _addressController._suffixController, - validator: suffixValidator, - label: suffixLabel, + controller: widget._addressController._suffixController, + fieldDecoration: widget.suffixDecoration, ), ], ), ), AddressFormTextField( - controller: _addressController._streetController, - validator: streetValidator, - label: streetLabel, + controller: widget._addressController._streetController, + fieldDecoration: widget.streetDecoration, ), AddressFormTextField( - controller: _addressController._cityController, - validator: cityValidator, - label: cityLabel, + controller: widget._addressController._cityController, + fieldDecoration: widget.cityDecoration, ), ], ); @@ -81,36 +82,35 @@ class AddressForm extends StatelessWidget { } class AddressFormTextField extends StatelessWidget { - final Widget label; - final TextEditingController controller; - final String? Function(String) validator; - const AddressFormTextField({ - Key? key, - required this.label, + AddressFormTextField({ + super.key, + required this.fieldDecoration, required this.controller, - required this.validator, - }) : super(key: key); + }) { + _addressFieldDecoration = fieldDecoration; + } - String? get _errorText => validator(controller.value.text); + final TextEditingController controller; + final InputDecoration fieldDecoration; + + late final InputDecoration _addressFieldDecoration; @override Widget build(BuildContext context) { return ValueListenableBuilder( - valueListenable: controller, - builder: (context, value, _) { - return Flexible( - child: Container( - margin: const EdgeInsets.all(10), - child: TextField( - controller: controller, - decoration: InputDecoration( - label: label, - border: const OutlineInputBorder(), - errorText: _errorText), - ), + valueListenable: controller, + builder: (context, value, _) { + return Flexible( + child: Container( + margin: const EdgeInsets.all(10), + child: TextField( + controller: controller, + decoration: _addressFieldDecoration, ), - ); - }); + ), + ); + }, + ); } } @@ -121,7 +121,14 @@ class AddressController extends ChangeNotifier { /// When the form changes, the function passes the current `AddressModel` as an argument and gives the possibility to manipulate and return a `AddressModel`. final FutureOr Function(AddressModel)? onAutoComplete; - AddressController({this.initialValue, this.onAutoComplete}) { + AddressController( + {this.initialValue, + this.onAutoComplete, + required this.zipCodeValidator, + required this.housenumberValidator, + required this.suffixValidator, + required this.streetValidator, + required this.cityValidator}) { _model = initialValue ?? const AddressModel( zipcode: null, @@ -140,6 +147,12 @@ class AddressController extends ChangeNotifier { late AddressModel _model; + final String? Function(String) zipCodeValidator; + final String? Function(String) housenumberValidator; + final String? Function(String) suffixValidator; + final String? Function(String) streetValidator; + final String? Function(String) cityValidator; + late final _zipcodeController = TextEditingController(text: initialValue?.zipcode); late final _streetController = @@ -152,6 +165,20 @@ class AddressController extends ChangeNotifier { AddressModel get model => _model; + bool get validate => _validate(); + + bool _validate() { + if (zipCodeValidator.call(_zipcodeController.text) == null && + streetValidator.call(_streetController.text) == null && + housenumberValidator.call(_housenumberController.text) == null && + suffixValidator.call(_suffixController.text) == null && + cityValidator.call(_cityController.text) == null) { + return true; + } else { + return false; + } + } + void _update() async { AddressModel updatedModel = _model.copyWith( zipcode: _zipcodeController.text, diff --git a/pubspec.yaml b/pubspec.yaml index ec8d961..989a71b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,6 @@ name: flutter_address_form description: A new Flutter package project. version: 0.0.1 -homepage: environment: sdk: '>=2.18.2 <3.0.0' diff --git a/test/flutter_address_form_test.dart b/test/flutter_address_form_test.dart index 56106d7..71896d2 100644 --- a/test/flutter_address_form_test.dart +++ b/test/flutter_address_form_test.dart @@ -11,45 +11,48 @@ void main() { home: Scaffold( appBar: AppBar(), body: AddressForm( - zipCodeValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (!zipcodeRegExp.hasMatch(text)) { - return 'Invalid zipcode'; - } - return null; - }, - housenumberValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (text.length >= 3 || int.tryParse(text) == null) { - return 'Invalid number'; - } - return null; - }, - suffixValidator: (text) { - if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { - return 'Invalid prefix'; - } - return null; - }, - streetValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - return null; - }, - cityValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - return null; - }, - controller: AddressController(onAutoComplete: (address) { - return address; - }), + onSubmit: (value) => value, + controller: AddressController( + zipCodeValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (!zipcodeRegExp.hasMatch(text)) { + return 'Invalid zipcode'; + } + return null; + }, + housenumberValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (text.length >= 3 || int.tryParse(text) == null) { + return 'Invalid number'; + } + return null; + }, + suffixValidator: (text) { + if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { + return 'Invalid prefix'; + } + return null; + }, + streetValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + onAutoComplete: (address) { + return address; + }, + cityValidator: (text) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + return null; + }, + ), ), ), ), From 3ba62681c9df13c22a1fe1e6d690e3ea2d975125 Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Tue, 25 Oct 2022 12:25:20 +0200 Subject: [PATCH 08/10] Added validator to AddressController --- example/lib/main.dart | 9 ++-- lib/src/address_form.dart | 87 +++++++++++++++++++++------------------ 2 files changed, 52 insertions(+), 44 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 9d712df..2bf2b41 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -86,10 +86,11 @@ class AddressFormExample extends StatelessWidget { AddressForm( onSubmit: (value) => value, controller: _addressController), TextButton( - onPressed: () { - _addressController.validate; - }, - child: Text('Test')) + onPressed: () { + _addressController.validate(); + }, + child: Text('Test'), + ) ], ), ); diff --git a/lib/src/address_form.dart b/lib/src/address_form.dart index 3493112..5621ae4 100644 --- a/lib/src/address_form.dart +++ b/lib/src/address_form.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:ffi'; import 'package:flutter/material.dart'; @@ -48,58 +47,68 @@ class AddressForm extends StatefulWidget { class _AddressFormState extends State { @override Widget build(BuildContext context) { - return Column( - children: [ - AddressFormTextField( - controller: widget._addressController._zipcodeController, - fieldDecoration: widget.zipCodeDecoration, - ), - Flexible( - child: Row( - children: [ - AddressFormTextField( - controller: widget._addressController._housenumberController, - fieldDecoration: widget.housenumberDecoration, - ), - AddressFormTextField( - controller: widget._addressController._suffixController, - fieldDecoration: widget.suffixDecoration, - ), - ], + return Flexible( + child: Column( + children: [ + AddressFormTextField( + validator: widget._addressController.zipCodeValidator, + controller: widget._addressController._zipcodeController, + fieldDecoration: widget.zipCodeDecoration, ), - ), - AddressFormTextField( - controller: widget._addressController._streetController, - fieldDecoration: widget.streetDecoration, - ), - AddressFormTextField( - controller: widget._addressController._cityController, - fieldDecoration: widget.cityDecoration, - ), - ], + Flexible( + child: Row( + children: [ + AddressFormTextField( + validator: widget._addressController.housenumberValidator, + controller: widget._addressController._housenumberController, + fieldDecoration: widget.housenumberDecoration, + ), + AddressFormTextField( + validator: widget._addressController.suffixValidator, + controller: widget._addressController._suffixController, + fieldDecoration: widget.suffixDecoration, + ), + ], + ), + ), + AddressFormTextField( + validator: widget._addressController.streetValidator, + controller: widget._addressController._streetController, + fieldDecoration: widget.streetDecoration, + ), + AddressFormTextField( + validator: widget._addressController.cityValidator, + controller: widget._addressController._cityController, + fieldDecoration: widget.cityDecoration, + ), + ], + ), ); } } class AddressFormTextField extends StatelessWidget { - AddressFormTextField({ - super.key, - required this.fieldDecoration, - required this.controller, - }) { - _addressFieldDecoration = fieldDecoration; - } + AddressFormTextField( + {super.key, + required this.fieldDecoration, + required this.controller, + required this.validator}); final TextEditingController controller; final InputDecoration fieldDecoration; + final String? Function(String) validator; - late final InputDecoration _addressFieldDecoration; + late InputDecoration _addressFieldDecoration; + + String? get _errorText => validator(controller.value.text); @override Widget build(BuildContext context) { return ValueListenableBuilder( valueListenable: controller, builder: (context, value, _) { + _addressFieldDecoration = + fieldDecoration.copyWith(errorText: _errorText); return Flexible( child: Container( margin: const EdgeInsets.all(10), @@ -165,9 +174,7 @@ class AddressController extends ChangeNotifier { AddressModel get model => _model; - bool get validate => _validate(); - - bool _validate() { + bool validate() { if (zipCodeValidator.call(_zipcodeController.text) == null && streetValidator.call(_streetController.text) == null && housenumberValidator.call(_housenumberController.text) == null && From 51de713b0eff19ba1a5ce7bb3138383dcb05267d Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Tue, 25 Oct 2022 15:43:08 +0200 Subject: [PATCH 09/10] Fixed Form With using FormKey --- example/lib/main.dart | 62 ++++++++++++-------- lib/src/address_form.dart | 90 ++++++++++++----------------- test/flutter_address_form_test.dart | 57 +++++++++++------- 3 files changed, 112 insertions(+), 97 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 2bf2b41..d0d3c95 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -37,59 +37,73 @@ class AddressFormExample extends StatelessWidget { final _addressController = AddressController( zipCodeValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (!RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$').hasMatch(text)) { - return 'Invalid zipcode'; + if (text != null) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (!RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$').hasMatch(text)) { + return 'Invalid zipcode'; + } } return null; }, housenumberValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (text.length >= 3 || int.tryParse(text) == null) { - return 'Invalid number'; + if (text != null) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (text.length >= 3 || int.tryParse(text) == null) { + return 'Invalid number'; + } } return null; }, suffixValidator: (text) { - if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { - return 'Invalid prefix'; + if (text != null) { + if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { + return 'Invalid prefix'; + } } return null; }, streetValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; + if (text != null) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + } + return null; + }, + cityValidator: (text) { + if (text != null) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } } return null; }, onAutoComplete: (address) { return address; }, - cityValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - return null; - }, ); @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(), + appBar: AppBar( + title: const Text('Address Form'), + ), body: Column( children: [ AddressForm( - onSubmit: (value) => value, controller: _addressController), - TextButton( + onSubmit: (value) => value, + controller: _addressController, + ), + ElevatedButton( onPressed: () { _addressController.validate(); }, - child: Text('Test'), + child: const Text('Validate'), ) ], ), diff --git a/lib/src/address_form.dart b/lib/src/address_form.dart index 5621ae4..5b5d10b 100644 --- a/lib/src/address_form.dart +++ b/lib/src/address_form.dart @@ -47,7 +47,8 @@ class AddressForm extends StatefulWidget { class _AddressFormState extends State { @override Widget build(BuildContext context) { - return Flexible( + return Form( + key: widget._addressController._formKey, child: Column( children: [ AddressFormTextField( @@ -55,21 +56,23 @@ class _AddressFormState extends State { controller: widget._addressController._zipcodeController, fieldDecoration: widget.zipCodeDecoration, ), - Flexible( - child: Row( - children: [ - AddressFormTextField( + Row( + children: [ + Expanded( + child: AddressFormTextField( validator: widget._addressController.housenumberValidator, controller: widget._addressController._housenumberController, fieldDecoration: widget.housenumberDecoration, ), - AddressFormTextField( + ), + Expanded( + child: AddressFormTextField( validator: widget._addressController.suffixValidator, controller: widget._addressController._suffixController, fieldDecoration: widget.suffixDecoration, ), - ], - ), + ), + ], ), AddressFormTextField( validator: widget._addressController.streetValidator, @@ -88,37 +91,26 @@ class _AddressFormState extends State { } class AddressFormTextField extends StatelessWidget { - AddressFormTextField( - {super.key, - required this.fieldDecoration, - required this.controller, - required this.validator}); + const AddressFormTextField({ + super.key, + required this.fieldDecoration, + required this.controller, + this.validator, + }); final TextEditingController controller; final InputDecoration fieldDecoration; - final String? Function(String) validator; - - late InputDecoration _addressFieldDecoration; - - String? get _errorText => validator(controller.value.text); + final String? Function(String?)? validator; @override Widget build(BuildContext context) { - return ValueListenableBuilder( - valueListenable: controller, - builder: (context, value, _) { - _addressFieldDecoration = - fieldDecoration.copyWith(errorText: _errorText); - return Flexible( - child: Container( - margin: const EdgeInsets.all(10), - child: TextField( - controller: controller, - decoration: _addressFieldDecoration, - ), - ), - ); - }, + return Container( + margin: const EdgeInsets.all(10), + child: TextFormField( + controller: controller, + decoration: fieldDecoration, + validator: validator, + ), ); } } @@ -127,17 +119,19 @@ class AddressController extends ChangeNotifier { /// An optional value to initialize the form field to, or null otherwise. final AddressModel? initialValue; + final GlobalKey _formKey = GlobalKey(); + /// When the form changes, the function passes the current `AddressModel` as an argument and gives the possibility to manipulate and return a `AddressModel`. final FutureOr Function(AddressModel)? onAutoComplete; AddressController( {this.initialValue, this.onAutoComplete, - required this.zipCodeValidator, - required this.housenumberValidator, - required this.suffixValidator, - required this.streetValidator, - required this.cityValidator}) { + this.zipCodeValidator, + this.housenumberValidator, + this.suffixValidator, + this.streetValidator, + this.cityValidator}) { _model = initialValue ?? const AddressModel( zipcode: null, @@ -156,11 +150,11 @@ class AddressController extends ChangeNotifier { late AddressModel _model; - final String? Function(String) zipCodeValidator; - final String? Function(String) housenumberValidator; - final String? Function(String) suffixValidator; - final String? Function(String) streetValidator; - final String? Function(String) cityValidator; + final String? Function(String?)? zipCodeValidator; + final String? Function(String?)? housenumberValidator; + final String? Function(String?)? suffixValidator; + final String? Function(String?)? streetValidator; + final String? Function(String?)? cityValidator; late final _zipcodeController = TextEditingController(text: initialValue?.zipcode); @@ -175,15 +169,7 @@ class AddressController extends ChangeNotifier { AddressModel get model => _model; bool validate() { - if (zipCodeValidator.call(_zipcodeController.text) == null && - streetValidator.call(_streetController.text) == null && - housenumberValidator.call(_housenumberController.text) == null && - suffixValidator.call(_suffixController.text) == null && - cityValidator.call(_cityController.text) == null) { - return true; - } else { - return false; - } + return _formKey.currentState!.validate(); } void _update() async { diff --git a/test/flutter_address_form_test.dart b/test/flutter_address_form_test.dart index 71896d2..202383a 100644 --- a/test/flutter_address_form_test.dart +++ b/test/flutter_address_form_test.dart @@ -4,8 +4,13 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_address_form/flutter_address_form.dart'; void main() { + late RegExp zipcodeRegExp; + + setUp(() { + // Testing with Dutch ZipCode + zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); + }); testWidgets('Render App with AddressForm Widget', (tester) async { - final RegExp zipcodeRegExp = RegExp(r'^[1-9][0-9]{3}\s?[a-zA-Z]{2}$'); await tester.pumpWidget( MaterialApp( home: Scaffold( @@ -14,44 +19,54 @@ void main() { onSubmit: (value) => value, controller: AddressController( zipCodeValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (!zipcodeRegExp.hasMatch(text)) { - return 'Invalid zipcode'; + if (text != null) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (!zipcodeRegExp.hasMatch(text)) { + return 'Invalid zipcode'; + } } return null; }, housenumberValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - if (text.length >= 3 || int.tryParse(text) == null) { - return 'Invalid number'; + if (text != null) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + if (text.length >= 3 || int.tryParse(text) == null) { + return 'Invalid number'; + } } return null; }, suffixValidator: (text) { - if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { - return 'Invalid prefix'; + if (text != null) { + if (text.isNotEmpty && RegExp(r'/^[a-z]*$/').hasMatch(text)) { + return 'Invalid prefix'; + } } return null; }, streetValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; + if (text != null) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } + } + return null; + }, + cityValidator: (text) { + if (text != null) { + if (text.isEmpty) { + return 'Can\'t be empty'; + } } return null; }, onAutoComplete: (address) { return address; }, - cityValidator: (text) { - if (text.isEmpty) { - return 'Can\'t be empty'; - } - return null; - }, ), ), ), From f4fe6e04c36a788c49fad532aa4216bd5eda5b09 Mon Sep 17 00:00:00 2001 From: Thomas Klein Langenhorst Date: Tue, 25 Oct 2022 15:49:49 +0200 Subject: [PATCH 10/10] added assert to validate --- lib/src/address_form.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/src/address_form.dart b/lib/src/address_form.dart index 5b5d10b..3378e3d 100644 --- a/lib/src/address_form.dart +++ b/lib/src/address_form.dart @@ -169,6 +169,8 @@ class AddressController extends ChangeNotifier { AddressModel get model => _model; bool validate() { + assert(_formKey.currentState != null, + 'Validation can only be used if a FormKey is attached to the current Form'); return _formKey.currentState!.validate(); }