An introduction to Flutter.
You need to have Android Studio and Flutter installed.
The documentation for the programming language ‘Dart’ can be found at: https://dart.dev/guides , The one for Flutter at https://flutter.dev/docs .
Create a new flutter project in Android Studio. Select ‘Flutter Application’. Open ‘main.dart’ in the ‘lib’ folder. There you will find generated code which you can delete.
We have to import Flutter and we need a main program:
import 'package: flutter / material.dart' ;
void main () {
runApp ( MyApp ());
}
Then we need a widget to start our application:
class MyApp extends StatelessWidget {
@override
Widget build ( BuildContext context) {
return MaterialApp (
title : 'Flutter Into' ,
theme : ThemeData (
primarySwatch : Colors .blue,
visualDensity : VisualDensity .adaptivePlatformDensity,
),
home : CookiePage (),
);
}
}
So far so good. You always need this code for every new app.
As you can see, we install the CookieHomePage()
.
You are probably familiar with the fortune cookies that you will receive from the Chinese along with the bill. If you break it you will find a wise saying in it.
We will write an app that shows us a new saying every time we shake the phone.
In Flutter, everything you see on the screen is made up of widgets. Widgets generally have an appearance and a functionality.
Flutter has a widget for almost everything. We can (and must) program our own widgets. For this purpose we will discuss some of the existing widgets such as Text
, ListTile
, RaisedButton
and so on use.
There are also widgets without visual representation. They are used to arrange other widgets. As an example Center
, Column
and should be mentioned here ListView
.
Widgets are arranged in a hierarchy. To do this, each widget has the property child:
or property children:
.
In this way we can create a hierarchical layout.
If we program our own widgets, we have to derive them from a suitable widget class and specify how our widget is put together.
This happens in the function Widget build(BuildContext context)
which we have to overwrite in our subclass.
Let’s write our first widget.
We want to display a text in the center of our page which contains the saying of the day.
So that our app looks like a real app, we Scaffold
will use a widget for the basic layout :
class CookiePage extends StatelessWidget {
@override
Widget build ( BuildContext context) {
return Scaffold (
appBar : AppBar (
title : Text ( 'Cookie of the Day' )
),
body : Center (
child : Text ( 'Should show a cookie' ),
)
);
}
}
Start an emulator under ‘Tools / AVD Manager’ and let the program run.
Next we need data. Let’s write a class that will manage our wisdom.
import 'dart: math' ;
class Cookies {
List < String > _cookies; // private member
Cookies () { // Constructor
_cookies = [
'The good day starts with getting up \ n the bad too' ,
'Even a blind hen finds a grain' ,
'42'
];
}
List < String > get cookies => List . unmodifiable (_cookies);
String get cookieOfTheDay => _cookies [ Random (). nextInt (_cookies.length)];
addCookie ( String wisdom) {_cookies. add (wisdom); }
}
Then we can complete our CookiePage
:
class CookiePage extends StatelessWidget {
final cookies = Cookies (); // <- new
@override
Widget build ( BuildContext context) {
return Scaffold (
appBar : AppBar (
title : Text ( 'Cookie of the Day' )
),
body : Center (
child : Text ( '$ { cookies.cookieOfTheDay }' ), // <- new
)
);
}
}
Select 'Run / Flutter Hot Restart ’ several times .
You should then see various pieces of wisdom.
Let’s create another page in which we can manage our cookies.
The upper half of the window should display a list of the existing cookies, below we will display a form for entering a new cookie.
We’ll create a new widget for this, this time one of type StatefulWidget
.
So what is a statefull widget and why do we need it?
In Flutter, all widgets are recreated each time you redraw. If these contain local data, this data is reinitialized each time.
But sometimes we want data (the state) to be retained between the new characters. That’s why we broke in StatefullWidget
.
Statefull widgets always consist of two parts, a widget and an associated state.
class CookieMaintenancePage extends StatefulWidget {
@override
_CookieMaintenanceState createState () => _CookieMaintenanceState ();
}
class _CookieMaintenanceState extends State < CookieMaintenancePage > {
@override
Widget build ( BuildContext context) {
// TODO: implement widget
}
}
The basic structure is always the same. The StatefullWidget overwrites the function createState()
and returns a suitable state implementation. In the State class we overwrite the function as usual build(...)
. All variables that are to survive the redraw are defined in the State class.
In the CookieMaintenancePage
widget we use against one Scaffold
as a framework. In the middle we have a column that shows the list in the upper part and the form in the lower part.
The cookies are defined in the state variable _cookies.
class _CookieMaintenanceState extends State < CookieMaintenancePage > {
@override
Widget build ( BuildContext context) {
return Scaffold (
appBar : AppBar (
title : Text ( 'Manage Cookies' ),
),
body : Center (
child : Column (
mainAxisAlignment : MainAxisAlignment .center,
children : [
Expanded (child : cookieList ()),
cookieForm ()
],
),
),
);
}
Widget cookieList () { return Container (); } // todo
widget cookieForm () { return Container (); } // todo
}
First we implement the list in the function cookieList()
:
Widget cookieList () {
return ListView . builder (
itemCount : _cookies.cookies.length,
itemBuilder : (context, index) {
return Card (
child : ListTile (
title : Text (_cookies.cookies [index]),
)
);
}
);
}
For an overview of how to create a text input in Flutter, please see https://flutter.dev/docs/cookbook/forms/retrieve-input .
We need one in the _CookieMaintenanceState class TextEditingController
and have to dispose()
override the function. Then we have to cookieForm()
implement the function .
class _CookieMaintenanceState extends State < CookieMaintenancePage > {
...
final myController = TextEditingController ();
@override
void dispose () {
myController. dispose ();
great . dispose ();
}
...
Widget cookieForm () {
return Column (
children : < Widget > [
TextField (controller : myController),
ElevatedButton (
child : text ( 'append' ),
onPressed : () {
if (myController.text.isNotEmpty) {
setState (() {
_cookies. addCookie (myController.text);
myController.text = '' ;
});
}
}
)
]
);
}
}
Ok, the code can be read somehow, but what’s this setState()
thing about?
Whenever we change the state of our application, the dependent widgets have to be redrawn.
Specifically, this means that the list of cookies has to be redrawn when we add new wisdom. But how is Flutter supposed to know that the condition has changed?
The function is used for this setState()
. You get a (callback) function as a parameter. It does this at the appropriate time and then causes the page to be redesigned.
In our case we define a function ‘on ther fly’. With () {}
we create a so-called lambda function. It doesn’t want any parameters and does whatever we put inside the curly braces. We pass this lambda function to setState () as an argument.
Then change the call home: CookiePage(),
in the MyApp class home: CookieMaintenancePage(),
and try out the code.
Next, let’s connect the two sides. It’s not that difficult. We simply install one IconButton
in the AppBar of CookiePage which sends us to the CookieMaintenancePage with the help of a navigator . We come back then simply with the ‘back button’.
class CookiePage extends StatelessWidget {
final cookies = Cookies ();
@override
Widget build ( BuildContext context) {
return Scaffold (
appBar : AppBar (
title : Text ( 'Cookie of the Day' ),
actions : actions (context), // <- new
),
body : Center (
child : text ( '$ { cookies.cookieOfTheDay }' ),
)
);
}
// new
List < Widget > actions ( BuildContext context) {
return [
IconButton (
icon : Icon ( Icons .edit_rounded),
onPressed : () {
Navigator . push (context,
MaterialPageRoute (builder : (context) => CookieMaintenancePage ()));
}
)
];
}
}
Let’s look at what we’ve done so far. The CookiePage is a StatelessWidget with a constant cookie which is re-instanced each time it is redrawn. We have implemented the CookieMaintenancePage as a StatefulWidget, which instantiates the _cookies variable exactly once in its state and which is retained for as long as the CookieMaintenancePage exists (is displayed).
class CookiePage extends StatelessWidget {
final cookies = Cookies (); // new instance on every redraw
...
}
class _CookieMaintenanceState extends State < CookieMaintenancePage > {
Cookies _cookies = Cookies (); // One instance for the whole lifetime of the page
...
}
So we have two different instances of the cookie data.
That’s not right. We need an instance which is used by both sides.
Flutter has no idea of how to solve the global state management problem. In the article State Management you will find an overview of what you could use.
Since Flutter recommends the provider pattern , I’ll show you this.
Provider is easy.
So let’s do that 😀
So that we can use the provider package, we have to specify in the ‘pubspec.yaml’ file that we need it. Open this file, search for the entry ‘dependencies:’ and adjust the entry as follows:
dependencies :
provider : ^ 4.3.3 ## <- new
flutter :
sdk : flutter
Our cookies class must ChangeNotifier
inherit from and notifyListeners()
call the function every time its internal state changes .
class Cookies extends ChangeNotifier { // <- new
...
addCookie ( String wisdom) {
_cookies. add (wisdom);
notifyListeners (); // <- new
}
}
We create main()
a cookies object in the function and pass this as a parameter to the MyApp
widget, which inserts it into the widget hierarchy. We do this by packing our MaterialApp into a provider widget:
import 'package: provider / provider.dart' ;
...
class MyApp extends StatelessWidget {
final cookies;
MyApp ( this .cookies);
@override
Widget build ( BuildContext context) {
return Provider < Cookies > ( // <- new
create : (_) => cookies, // provide cookie data
child : MaterialApp (
...
)
); // <- new
}
}
In the CookiePage we delete the constant cookies and get the required data from the provider at the beginning of the build () function. The rest remains as usual.
class CookiePage extends StatelessWidget {
// <- deleted
@override
Widget build ( BuildContext context) {
var cookies = Provider . of < Cookies > (context); // <- new
return Scaffold (
appBar : AppBar (
title : Text ( 'Cookie of the Day' ),
actions : actions (context),
),
body : Center (
child : text ( '$ { cookies.cookieOfTheDay }' ),
)
);
}
...
}
We do the same thing in _CookieMaintenanceState.
However, the effort is a bit greater because we have outsourced the creation of the form and the ListView to two functions. In each of these functions, we need access to the cookie data. We can only find the right provider if we have the current context. We must therefore transfer this when calling the functions and also receive it there.
As for the simplicity, I’ll give you the whole code below.
class _CookieMaintenanceState extends State < CookieMaintenancePage > {
// <- deleted
final myController = TextEditingController ();
@override
void dispose () {
myController. dispose ();
great . dispose ();
}
@override
Widget build ( BuildContext context) {
return Scaffold (
appBar : AppBar (
title : Text ( 'Manage Cookies' ),
),
body : Center (
child : Column (
mainAxisAlignment : MainAxisAlignment .center,
children : [
Expanded (child : cookieList (context)), // <- changed
cookieForm (context) // <- changed
],
),
),
);
}
Widget cookieList ( BuildContext context) { // <- changed
var _cookies = Provider . of < Cookies > (context); // <- new
return ListView . builder (
itemCount : _cookies.cookies.length,
itemBuilder : (context, index) {
return Card (child : ListTile (
title : Text (_cookies.cookies [index]),
));
}
);
}
Widget cookieForm ( BuildContext context) { // <- changed
var _cookies = Provider . of < Cookies > (context); // <- new
return Column (
children : < Widget > [
TextField (controller : myController),
ElevatedButton (
child : text ( 'append' ),
onPressed : () {
if (myController.text.isNotEmpty) {
setState (() {
_cookies. addCookie (myController.text);
myController.text = '' ;
});
}
}
)
]
);
}
}
Not bad. With just 142 lines of code, we wrote a complete app.
It demonstrates how we switch between different pages, that there are stateless (StatelesWidget) and stateful (StatefullWidget) and how we can install ‘global’ state so that it can not only be used in all widgets, but also triggers automatic redrawing if his condition changes.
The only thing that is missing now is the possibility to order a new fortune cookie by shaking it on the CookiePage.
Flutter makes it possible to create applications for the web, the desktop and for mobile devices. Both Android and the Apple operating system are supported on the mobile devices. Ideally, you write code once and the app runs everywhere.
We generally only find sensors in mobile devices. They are addressed and evaluated by drivers of the corresponding operating system. Since Flutter is a cross-platform development environment, it must communicate with the existing operating system, which in turn communicates with the sensor hardware.
In Flutter there is the possibility to write code which calls platform-specific code. We can then write code for each operating system that omits the sensors and takes care of communication with Flutter. For this we have to write platform-specific code for each supported platform.
But that’s exactly what we don’t want. Let someone else do it for us, please😈.
So we need a suitable library.
on https://pub.dev/ we can search for suitable libraries. Let’s try the sensors package. According to the installation instructions, we add to our pubspec.yaml file.
dependencies :
provider : ^ 4.3.3
sensors : ^ 0.4.2 + 6 ## <- new
flutter :
sdk : flutter
The sensors package gives us access to the acceleration and gyroscope sensors.
You can find an example of how we handle sensor data under SensorPage .
We would certainly be able to program a shake detector with the existing sensor data. Fortunately, such a library already exists and we will use it.
Install shake .
dependencies :
provider : ^ 4.3.3
shake : ^ 0.1.0 ## <- new
flutter :
sdk : flutter
Unfortunately, the shake sensor has to be used in a StatefulWidget. So we adapt our CookiePage accordingly and add a initState()
function according to the example from shake. In onPhoneShake:
we do not have to do anything except call setState (), a redraw is triggered automatically. This in turn acquires a new piece of wisdom in terms of the cookies data structure.
class CookiePage extends StatefulWidget {
@override
_CookiePageState createState () => _CookiePageState ();
}
class _CookiePageState extends State < CookiePage > {
@override
void initState () {
great . initState ();
ShakeDetector detector =
ShakeDetector . autoStart (onPhoneShake : () {
setState (() {}); // Force redraw
});
}
...
}
Flutter tries to protect us from mistakes. To do this, it analyzes the code and, if necessary, issues warnings on the screen.
The most important part of the error message is:
This is likely a mistake, as Provider will not automatically update dependents when Cookies is updated.
Flutter noticed that our page will not be automatically redrawn if the cookie data changes.
But that’s exactly what we want. We do not want new wisdom when something has changed in the cookie data, but only when we ask for new wisdom by shaking it.
As a solution, Flutter suggests to suppress the analysis output in main (). And that’s exactly what we’re doing now:
void main () {
Provider .debugCheckInvalidValueType = null ; // <- add this to disable check
runApp ( MyApp ());
}
Now the thing should actually work 😀
Note, however, that such mechanisms should only be switched off if you are really sure that you know better.
The SensorPage only shows the bare essentials. We need a StatefulWidget so that we can attach ourselves to the initState()
function in the accelerometerEvents
. dispose()
We then log off again in the function. In the callback function, we only accept every 20th event, copy the received values into the local state and trigger the redraw.
In the build()
function we create a rudimentary GUI to display the data.
Note that we directionIcon()
convert the data in the function into directional information using a threshold value. Never test for a specific sensor value but always against a threshold or an interval. Sensor values are tainted with noise and it is possible that a certain value never occurs.
import 'package: flutter / material.dart' ;
import 'dart: async' ;
import 'package: sensors / sensors.dart' ;
class SensorPage extends StatefulWidget {
@override
_SensorPageState createState () => _SensorPageState ();
}
class _SensorPageState extends State < SensorPage > {
int delayCount = 0 ;
double _ax = 0 , _ay = 0 , _az = 0 ;
StreamSubscription < dynamic > _accelerometerSubscription;
void initState () {
super . initState ();
// Subscribe for accelerator events
_accelerometerSubscription = accelerometerEvents. listen ((event) {
// We do not need evey event
if ( ++ delayCount < 20 ) return ; delayCount = 0 ;
// whenever we get new data, force redraw by calling setState ()
setState (() {
// Copy values to local state
_ax = event.x; _ay = event.y; _az = event.z;
});
});
}
void dispose () {
super . dispose ();
_accelerometerSubscription. cancel ();
}
@override
Widget build ( BuildContext context) {
return Scaffold (
appBar : AppBar (
title : Text ( 'Sensor' ),
),
body : Center (
child : Column (
children : [
Expanded (child : Center (child : directionIcon ( 2.5 ))),
Text ( 'Accel: x: $ { _d2s (_ax) }, y: $ { _d2s (_ay) }, z: $ { _d2s (_az ) } ' , textScaleFactor : 1.5 ,),
],
),
));
}
Widget directionIcon ( double threshold) {
if (_ay < - threshold) return Icon ( Icons .arrow_upward);
if (_ay > threshold) return Icon ( Icons .arrow_downward);
if (_ax < - threshold) return Icon ( Icons .arrow_left_sharp);
if (_ax > threshold) return Icon ( Icons .arrow_right_alt);
return Icon ( Icons .account_circle_outlined);
}
String _d2s ( double d) => d. toStringAsFixed ( 2 );
}
Author: maexeler
Source Code: https://github.com/maexeler/flutter_intro
#flutter #dart #mobile-apps