How to create Forms in Flutter (Flutter Form Builder Tutorial)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video i'll show you how to easily create forms in flutter without the typical boilerplate that comes with it to do that we'll take a look at a powerful package that lets you create full featured forms from a small login form to complex forms where you can validate input data display appropriate error messages in the right language and create dynamic input procedures this package is called flutter form builder there have been many changes since my last tutorial and the package is now available in version 4.2 in this tutorial you will learn step by step all the useful features of the package so you can use it profitably for your future projects if you want to watch only certain parts of the video you can use the time timestamps to skip ahead to the corresponding part however if you have never heard of this package i recommend watching the tutorial from the beginning to the end and if you have watched the video i would really appreciate a quick feedback from you i put a lot of effort into this tutorial and hope that it will help you to better understand this package so let's get started thank you very much for your attention and enjoy watching before we start setting up the package i would like to take this opportunity to briefly draw attention to the developers working on this package mr denver miller and numerous other developers are continuously working to extend the feature set correct existing bucks and generally improve the package if you want to support this package you can contribute by giving the pubdev documentation site a like the github repo a star and if you want to go one step further go to mr miller's buy me a coffee site and buy mr miller a tasteful coffee to set up the package first go to the documentation page click on the installing tab copy the dependency line and paste it into your pubspec yaml file under the dependencies section and save the changes to check if the package has been successfully downloaded and installed see if the form builder widget name appears in the autocomplete dialog by adding the widget to the widget tree a new import statement should appear at the very top alternatively you can manually insert the import statement by copy and pasting in the file you want to use the package the core of the flutter form builder package is the form builder widget this widget is the glue that holds everything together so to speak therefore in order to create fully functional forms we should familiarize ourselves with its properties the first and one of the most important properties is the key property unfortunately we cannot view or manipulate the forms data through the widget itself in order to still be able to use all the important functions of the form such as reading modifying entries validation and so on we sneak another object into the form builder widget and this object is a so called global key so we create a global key object pass it to the formbuilder widget using the key attribute and then use this object to view and manipulate the state of the form there are two important details to keep in mind first we create the global key of type formbuilder state and second we created outside the build method so that it is not regenerated with every build cycle and now with this form key we can view modify and process the form data how this works exactly i'll go into in the course of the video the next property is the child's property this should be familiar to most of you the child property is the container for our form fields and the only required parameter which is why we still get an error displayed here for demonstration purposes i create a very simple form by adding a column containing a text field and a button then we have the unchanged property and as the name implies this is triggered whenever a form field has changed as an example i provide a simple print function which prints a text to the console but you can use any callback function of your choice now whenever we make changes on any form field of the form the unchanged callback function that we've provided is called as you can see even tapping into the text field is handled as a change and of course on every single keystroke within the text field the unchanged function is called as well with autovalidate mode we can change how validation is handled there are three modes that we can use by providing an auto validate mode object with auto validate mode always we can auto validate the form and form fields even without user interaction select disabled to disable the auto validation and select on user interaction to only validate after each user interaction later we will talk about validation in detail and we will have a look on how the form acts on every single mode next is on willpop which needs a function returning a future of type boolean and if that callback returns a future that resolves to false the forms route will not be popped in other words you can prevent users from leaving or closing the form to demonstrate this i will use my pre-build example app where i implemented every single aspect of this tutorial beforehand to familiarize myself with the package and for you guys to have an example app that you can always refer to if you want to use this app the link to the github repo is in the video description so let's navigate to another screen with a form that has an on willpop implementation so here we can see an example of a form builder widget with a very simplified callback function just for demonstration purposes this function returns false and therefore we are not able to pop this route but if this function was returning true then we would be able to go back to the previous screen then we have a property called initial value and by providing a map of string dynamic we can set initial values for each of our form fields in this case we just have one field which is our text field and the name of this text field is also text field and this name is the identifier that we have to use to set an initial value for this particular field and within the map we add the name of the field as a key and the content that we want to be displayed initially as a value for that key and now our text field displays the initial value and finally we have the property skip disabled to explain this i have to mention one piece of information in advance namely that form fields have a property called enabled which takes a boolean and setting it to false would disable the field and with skip disabled we can determine whether the form should ignore disabled fields perhaps you are now wondering when exactly the fields are ignored and that's why next we'll look at the basic functions of the form with flutter form builder you can easily reset your form we can reach all important functions through the global key which we created at the very beginning here we have a simple form a text field and a reset button to reset the form by clicking on the button we use our form key inside of the on-pressed function the form key gives us access to the current state of the form and this state object has a method called reset if you want you can also make the keyboard disappear by using this statement but that's optional the app is already running using this implementation that's why i don't have to save the file and now by clicking the button we can empty the form field the global key also gives us access to the current value of a field therefore we once again use our form key variable to get the current state of the form which is of type form builder state this object has a getter called fields which returns us a map of string form builder field state and if we jump into the form builder field state class we can see that this extends form field state and the class form field state has a getter called value which returns us the current value of the form field and because form builder field state is extending form field state it also has this scatter so in order to get the value we use the name of the field which is the identifier as the key and then the getter method value also notice the value that is returned is of type dynamic if you continue to work with this value you might have to convert it first now let's save that value in a variable and to display it i create a simple snack bar that pops up at the bottom of the screen and as you can see we can easily access the content of this text field okay you might be wondering why i'm going into two functions right now saving and reading the form this has to do with how the form handles the data unlike the previous lesson where we read a single form field now we want to read the entire form this means the input of all form fields as you might have guessed the inputs of all form fields are combined into one map of string dynamic as before we need to access the current state again this time however we don't want a single field but all fields at once this is easy because the form builder state class which we can access with dot current state also has a getter named value that returns the entire input as a map of string dynamic as we did with the form fields we store the return in a variable and display the contents with a snack bar but as we can see our map is empty and this is because we have to save the inputs first and we can do that with the safe method when we call this method then all the inputs are saved it is also possible to save specific fields by accessing the respective field as before because also the class form field state has a save method this way we can flexibly decide which field inputs to save and which not now that we know what the form is capable of i'd like to return to an unresolved issue i raised at the very beginning when talking about form builder properties more precisely it was about the property skip disabled and what exactly can be understood by skipping disabled fields here we have two text fields the first one is enabled and the second one is disabled if we save and read the data we can see both fields have been saved now let's see what happens if we set skip disabled to true the form behaves as if the second text filter does not exist up to this point we've covered how to reset the form how to read the data of certain fields or all fields at once and how to save the inputs now let's have a look at the last piece of the puzzle how to validate the user input later in the tutorial we will cover the topic of validation independently we'll look at built-in validators how to create a custom one how to perform multiple validations how to create conditional validations and how to create custom error messages but first let's get to the basics let's have a look at the example app we have a simple text field that requires a certain user input which is the word yes if we leave the text field empty or enter something different an error message appears below the text field which says this field value must be equal to yes in order to implement such a validation behavior two things have to be done first we must define for the text field what it should validate and second we use our global key as before to perform the validation one property or so-called core attribute all fields have in common is the attribute validator to this we can pass one of the built-in validators as i said later we will look at all the built-in validators one by one but to touch on the subject here's an example all of the built-in validators can be found through the class form builder validators to check if an input equals a certain value in our case the word yes we can call the equal validator method this needs the build context and the comparison value next we need to perform the validation which we usually do before the form is submitted so within the onpressed function of our submit button as always we use the form key to get the current state and then we call the method validate which returns true if the validation passed or false if the validation failed for example we could arrange for inputs to be saved only if the validation was successful this example can also be implemented in a shorter way by using the method save and validate but keep in mind by using safe and validate the form will be saved regardless of the validation result as you can see in this example next let's look at the core attributes these are the attributes that all fields have in common you already know some of them and basically they are all self-explanatory but for the sake of completeness let's briefly go through them the name attribute is the unique identifier of the field whenever you read a field or pre-populate it by setting its initial value you have to provide the name of the field as the key to retrieve or manipulate its current value you can pre-populate form fields with the initial value attribute there are two ways to do this either directly by the field or by the form builder widget both of them have this attribute but whereas with the fields you can specify the value directly with the form builder widget you have to pass a map of string dynamic with a key value pair for each field you can disable fields by setting the attribute enable to false but keep in mind the input value of a form field is saved even if the form field is disabled only if the skipped disabled attribute of the form builder widget is set to true disabled form fields are ignored with the decoration attribute you can style your fields and this should be self-explanatory with the validator attribute you can set conditions for the corresponding form fields that must be met for validation to be executed successfully for example we could say that only the word yes is accepted as a valid input you can use predefined validators as well as your own you can combine multiple validators and even attach them to certain conditions just like the form builder widget the form fields also have an unchanged attribute in the chapter about the form builder basics i have already explained how this works and finally the attribute value transformer with value transformer you can change the value of an input field before it is saved we can see a small example here we transform the value to uppercase before saving it one thing that makes the package immensely useful are the pre-made fields if i count it correctly there are currently 24. it would take too long to explain them all in detail however we will go through them one by one so that you get an overview of which fields we have what they look like what function they have and how the return value looks like okay let's get started first one is the classic checkbox which can either be true or false or null if the property tristate is set to true checkbox group creates a list of checkboxes for selecting multiple options and returns a list of the selected items chips input displays selected entries from a drop-down list in a chip-shaped preview in addition the list is filtered according to the input choice chip is like radio buttons but visually more appealing again we have a chip view from which we can make a selection with color picker fields you can display a very user-friendly selection dialog from which you can choose a color of your choice also daytime picker shows you a very user-friendly selection dialog to set date and time with date range picker we have the same thing but here we can select a time period then we have the classic drop down menu that shows you a listing from which you can select an entry filter chip is like checkbox group but also with the chip design you can select multiple items which will be marked with a check mark radio group should be familiar to everyone here you also have one option to select with range slider you can define a range by setting a minimum and maximum value and then select a range that is between the boundaries the ratings field works similar to amazon's rating system where you can choose between 1 and 5 stars searchable drop down is like the classic drop down but here you can enter a search term and the selection list gets filtered segmented control is similar to radio group where you can select one of the given options but it has a different ui signature pad lets you write your signature and returns the coordinates of the drawing slider lets you choose a numeric value within a predefined range switch is similar to a single checkbox you can turn it on or off which returns either true or false then of course there's the text field that we've already seen a few times touchspin displays an increase and decrease icon to select a numeric value you can define the min max and step value type ahead is like the searchable drop down you can also enter a search term to filter the item list with file picker you can pick a file from your device from google drive or the gallery app same goes for image picker but here of course you can only pick image files with location fields i guess you can select a location but to make this work you need a google maps api key and last but not least the phone field with this field you can choose the country code from a list of countries and enter a phone number in addition the national flag of the selected country is displayed if this large selection of fields is not enough for you there's also the possibility to create your own custom fields here we have an example of a custom form fields which i found in the documentation to build your own custom fields you can use the form builder field widget this one has two required parameters name to be able to identify it and builder which is a function that takes a form-field state of dynamic and returns a widget in this example we return an input decorator which is like the frame of our input field it is responsible for displaying the label text we can create a padding around our actual field widget we can define a border and an arrow text among a lot of other options to define the frame it requires an input decoration object and the actual content which is our custom field is passed to the child attribute for example a container with a height of 200 and a child of cupertino picker with an item extend of 30 and the options that we want to display are taken by the children attribute as a list of widgets we define this list at the top because we also need it for the unselected item changed attribute this takes a function with an integer as input which is the index that is currently selected so whenever we select a new value this function is triggered and because of that we have access to the new index to save the change within our fields state and to actually change the field state we can call the did change method and pass in the selected value which we get from the options list using the index variable this is how you could create a custom field in september 2020 mr miller also wrote a medium article about how to turn any flutter widget into a form input however i don't know how up to date this is and if it still works the same way today but i think as an additional reference it can help link in the video description if you need to change the values of any field programmatically you can easily do that to change the value of a specific field use the global key to access the current state of the form specify the field with the fields property and then call the did change method that's what i already spoiled in the previous part alternatively you can also change values calling the patch value on the current state object and pass a map to override the fields to validate form inputs flutter form builder provides many built-in validators all of them can be called using the class form builder validators followed by a function call for the specific validation type the credit card's validator requires the fields value to be a valid credit card number the date string validator requires the fields value to be a valid date string you can check for valid email addresses you can check for equality or inequality you can check if the input is a valid integer you can check for ip addresses so four numbers ranging from 0 to 255 separated by dots with match you can provide a regular expression and in this example we see the one for the email validation you can set a max value you can set the max length for the input the minimum value the minimum length of the value you can make the fields value to be numeric only you can forbid to leave the field empty and you can check for urls now i will show you how to create a custom validator we are back to the form basic screen where i explained how to validate the form input we have a text field with a prebuilt validator which checks for equality and only the word yes is accepted as valid input let's recreate this validator using our own validation function if we have a look on the validators property we can see that the formbuilder validators object is not necessary we just need a function that takes a string and returns a string and that's pretty easy to create so let's delete this validator and instead use an anonymous function with a variable called value and within the body we check if value equals yes if it doesn't we return a string that says answer must be yes and if the value is equal to yes then we just return null let's save and test it and as you can see we implemented the same functionality but wrote our own custom function you can also use multiple validators at once let's say we want someone to enter a number in the text box and that number has to be in a range from 0 to 100 so we would have to check the entered value for three conditions first the input must be an integer second the input should be greater than or equal to zero and third the input should be less than or equal to 100. if we wanted to continue using our own validator for this we could add more if statements but there's a much more convenient way we can combine multiple validators by using the compose method from the form builder validators class the same class that contains the validation methods as you can see the compose method needs a list of functions returning a string so we provide a list with three validators integer min and max let's see if everything works perfect in addition we can also add our own validators here let's say we want to accept only numbers that are even we can just add another custom validator for that here we have an example for conditional validation which i got from the documentation it asks to select a programming language and only if we choose the entry other we have to specify more details in the text field below otherwise we don't so the text field may be empty unless we have selected other so we need a custom validation function for the text field in which we check which value was selected and as you probably know we need our global key for this again we get the selected value check if it's equal to other and if the text field is null or empty there are cases where the existing error messages are not sufficient that's why i'm going to show you how to create your own error messages let's assume that we have a form to register where we have to enter an email address and if we enter an email address that already exists that should also be displayed as error text to do this we define an empty variable for the arrow text at the top before the build method and a method that just serves as a simple example we have a list with the already existing email addresses which is like our database and it is queried whether the entered email address already exists using the input declaration of our form builder text fields we can also specify the error text we use the arrow text variable and as long it is now no text will be displayed which is why we need to implement the logic to change the value of the error text variable whenever an existing email address has been submitted so within the on pressed method of our submit button we get the current value and then check if the email exists using the email exists method that we defined at the top and in any other case we don't want the error text to be displayed therefore we set the email arrow variable back to null now that we've seen how validation works let's have a look at how the auto validation modes work here we have a checkbox field where autovalidate mode is set to always that's why it's already displaying the error message the checkbox has to be checked and here's our old good text field that wants only yes as valid input and here the error message appears as soon as we tap into the field which is our user interaction if we set it to disabled there is no auto validation but don't get me wrong the fields validators are still working but it's not automatically validating before i set the auto validate modes on the fields i tried it on the form builder widget but there the auto validate mode always behaves the same way as the on user interaction mode so if you want the auto validation always to be active better set it in the field instead the form builder widget let's move on to the final lesson of this tutorial how do we enable internationalization in flutter form builder it took a while for me to get it right but basically it's very easy our device language is set to spanish yet our error text is displayed in english we want to change that first we need to add a few entries to the pubspec yammer we add flutter locations and the intl package let's save and now we just have to modify our material app we add the supported locals and the localizations delegates you can find this code in the documentation let's save and restart the app and as you can see our error message is displayed in spanish and if we change back to english our app language changes as well and that brings us to the end i hope you enjoyed the tutorial and that it helps you to implement the package in your future projects if you use the package and think the project is worth supporting don't forget to like the documentation give a start to the github repository and show some appreciation to the developers through the donation links also i have donation accounts as well if you would like to support me in my mission that would help me a lot and if you liked the video and want to support me and my channel feel free to do so by liking sharing the video and subscribing to the channel all important links and also further information can be found in the video description down below if you have any questions thoughts or recommendations feel free to post them in the comments in case of technical issues regarding the package i advise you to report it directly to the developers by opening a case on the github repo site thank you for your attention i wish you a wonderful day and see you soon you
Info
Channel: SyntacOps
Views: 20,093
Rating: undefined out of 5
Keywords: how to create forms in flutter, how to create and validate forms in flutter, how to create adn validate forms in flutter, how to build forms in flutter, how to make forms in flutter, flutter form, flutter forms tutorial, flutter form validation, create form flutter, flutter form package, flutter form builder, flutter forms builder, flutter form design, flutter form ui, flutter form example, flutter form key, flutter forms app, flutter forms ui, flutter user input
Id: eGwq3_0K_Sg
Channel Id: undefined
Length: 36min 35sec (2195 seconds)
Published: Fri Feb 12 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.