Using stateful widgets

Let's now transform the MyApp class into a stateful widget, so that you can see the different implementations of the class:

class MyApp extends StatefulWidget {

You can see immediately that you get two errors. If you hover over the MyApp class, the error that you see is Missing concrete implementation of StatefulWidget.createState, and if you hover over the build method you see “The method doesn't override an inherited method.

What these errors are trying to tell us is the following:

  1. A stateful widget requires a createState() method.
  2. In a stateful widget, there is no build() method to override.

Let's fix both these issues using the following steps:

  1. Add the necessary createState() method, which will return MyAppState, which we'll create shortly. In the MyApp class, just under its definition, write the following code:
@override
MyAppState createState() => MyAppState();
  1. Create a new class called MyAppState, that extends the State, and in particular, the State of MyApp:
class MyAppState extends State<MyApp> {}
  1. In order to solve the second error (“Missing concrete implementation of State.build”), cut the build() method that is now in the MyApp class, and paste it into the MyAppState class. The revised code should look like this:
import 'package:flutter/material.dart';

void
main() => runApp(MyApp());

class
MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}

class
MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Measures Converter',
home: Scaffold(
appBar: AppBar(
title: Text('Measures Converter'),
),
body: Center(
child: Text('Measures Converter'),
),
),
);
}
}

To sum it up, from a syntax perspective, the difference between a Stateless widget and a stateful widget is that the former overrides a build() method and returns a widget, whereas a stateful widget overrides a createState() method, which returns a State. The State class overrides a build() method, returning a widget.

From a functional point of view, in the code that we have written, there is no difference whatsoever between the two, as in both cases the app looks and behaves exactly in the same way. So, let's add a feature that requires a stateful widget, and could not be achieved with a Stateless Widget.

Here, you can see the app layout so far:

Next, let's see how to read the user input from TextField.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.187.62