Flutter - Code Basics
Table of Contents
Code Basics
the main.dart file executes the app with the following convention
void main() => runApp(MyApp());
MyApp()
is a class that extends either a StatelessWidget
or StatefulWidget
. In general if the content of the screen is not going to change its display it should be stateless. StatfullWidgets require additional code we’ll review in a minute.
StatelessWidget
the basic class definition is simple
class MyApp extends StatelessWidget {
}
We’re going to override the build
method for the Stateless Widget and return our main display.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ...
}
}
specifically what we’re going to return is another widget, any widget, but in this case a special Widget called MaterialApp
that provides a material header theme look and feel. It takes parameters for title
, theme
and home
MaterialApp(
title: 'Flutter Demo',
theme: themeData(
primarySwatch: Colors.blue,
),
home: ... ,
);
And you guessed it, home
refers to another widget, any widget, in this case it will be our custom homepage screen.
Here’s the full class code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Welcome to Flutter'),
),
body: Center(
child: Text('Hello World'),
),
),
);
}
}
[[../../../_notes/_tech/Flutter/Flutter|Back to Flutter]]
StatefulWidget
Stateful widgets require a second class to take care of the state management. That second class extends the State component defining the type of the class it’s going to manage.
The StatefulWidget class is, itself, immutable and can be thrown away and regenerated, but the State class persists over the lifetime of the widget…Much like a stateful Kubenetes workload has a pod and a stateful disk. The pod can go away but the disk remains
class MyHomePage extends StatefulWidget {...}
class _MyHomePageState extends State<MyHomePage> {...}
The main class uses that State class by defining it through the createState()
function
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {...}
the state
class can alter the state of the main class by calling the setState()
function, which in turn calls the build()
method to repaint the display
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return ...
}
}
[[../../../_notes/_tech/Flutter/Flutter|Back to Flutter]]