Learn Dart Programming - Build Default Flutter Counter App
Victor Wooding
In today’s video we are going to be building the default app that is generated whenever we create a flutter project. This app is going to have an app bar, a text widget and a floating action button. We are going to build it from scratch and I am going to show you how to organize your code in different files.
Create a new project. I am going to name my project “using buttons”. Set the languages to Java and Swift and add an organization identifier. For this tutorial I recommend that you use a physical device. I had difficulties getting the button text to display but when it ran on the emulator there were no issues.
Delete the default code except the first line. That allows us to use material in our app. Delete the widget_test.dart file. Next create a directory in the lib folder and name it UI. Let’s create a dart file and name it home. Import material and then return to main.dart.
In order to use this dart file that we just created we need to import it. We type dot and this takes us to the root folder then we type forward slash and this allows us to access the ui folder. Then we type the name of the file that we created and we include the extension.
The main method is the entry point into our app and we are going to call runApp inside of this method. Inside of this method we are going to create a new Material app and we are going to give it a title. I’m going to name it using buttons and we are going to set the home to a home object.
In home.dart create a class Home which extends a stateful widget. A stateful widget has properties that are mutable. If you have variables or a text widget for example and you intend to change their value, then you should use a stateful widget. Right click on home and add the missing override and it presents us with this method called create state which returns a state. A state is made up of a list of stateful widgets. We are going to set it to return new HomeScreenState which is a class that we haven’t create yet. Right click on HomeScreenState to create the class.
We are going to extend State and pass in our Home widget. Right click on Home Screen State and add the missing override. Next let’s create a variable called counter and give it the underscore prefix because we want it to be private and give it an initial value of zero.
Next create a method which increases this counter value. We need to call setState inside of this method and pass in our method body. For more information on setState check the documentation in the link below. In this method we just want to increase the counter by 1.
We now need to build the user interface and we can do this using the scaffold material widget. The scaffold helps you with your material design widgets. This widget has the app bar so let’s create a new app bar ... https://www.youtube.com/watch?v=qavEFwuRxTs
34375883 Bytes