🎉 New release for Pusher Chatkit - Webhooks! Extend your in-app chat functionality
Hide
Products
chatkit_full-logo

Extensible API for in-app chat

channels_full-logo

Build scalable realtime features

beams_full-logo

Programmatic push notifications

Developers

Docs

Read the docs to learn how to use our products

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Sign in
Sign up

First steps with Flutter - Part 3: Responding to user input

  • Suragch
December 22nd, 2018
You will need a Flutter development environment set up on your machine.

This is a three-part series. You can find the other parts here:

Introduction

In the two previous tutorials we saw that widgets are blueprints for everything that you can see (and many things that you can't see) in the user interface. Simple widgets can be combined together to make complex layouts. The majority of these layouts can be built by dividing your design into rows (use the Row widget), columns (use the Column widget), and layers (use the Stack widget).

The thing about those layouts, though, is that they were static. You could touch and tap and swipe them all day and they wouldn't do a thing. We are going to fix that in this lesson.

Today we’re going to explore how to actually do something when the user interacts with the widgets that we’ve added to our layout. The emphasis will be on simple, easy to reproduce examples. I strongly encourage you to work along as we go through each one. Make little changes to the code and see how that affects the behavior. This will greatly increase your overall learning.

Prerequisites

This tutorial is for beginning Flutter developers. However, I’m assuming that you have the Flutter development environment set up and that you know how to create basic layouts using widgets. If not, refer to the following links:

In this tutorial we’ll start to do a little more programming with the Dart language. I’m assuming that you have a basic knowledge of object oriented programming, but I don't assume that you know Dart.

This lesson was tested using Flutter 1.0 with Android Studio. If you are using Visual Studio Code, though, it shouldn't be a problem. The commands and shortcuts are a little different, but they both fully support Flutter.

Review exercise

Before I give you the boilerplate code that we’ll use in the examples below, let's see if you can create the following layout on your own.

How did you do? If you weren't able to do it, you might want to check out the previous lesson on building layouts. You may have created something like this:

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

    class MyApp extends StatelessWidget { //            <---  StatelessWidget
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          ...
            body: myLayoutWidget(),
          ...
    }

    Widget myLayoutWidget() {
      return Column(
        children: [
          Text(...),
          RaisedButton(...),
        ],
      );
    }

Widgets and state

That layout above was fine as far as layouts go, but if you try to change the text when the button is pressed, you’ll run into problems. That's because widgets are immutable: they can't be changed. They can only be recreated. But to recreate the Text widget we need to put the string into a variable. We call that variable the state. It’s similar in idea to the phrases “the state of affairs” or a “State of the Union Address,” which deal with the current conditions of some people or country. Similarly, when we talk about a widget, the state refers to the values (in other words, the current condition) of the variables associated with that widget.

You notice in the code above that it's a StatelessWidget. StatelessWidgets don't have any state. That is, they don't have any mutable variables. So if we have a variable that we want to change, then we need a StatefulWidget.

StatefulWidgets work like this:

  • There is a StatefulWidget class and a State class.
  • The StatefulWidget class initializes the State class.
  • The State class holds the variables and tells the StatefulWidget class when and how to build itself.

Note: Behind the scenes there is also an Element that is created from the widget. But as I said, it's behind the scenes and we can happily ignore it at this point in our journey.

So practically speaking, whenever we need a StatefulWidget, we have to create two classes, a widget class and a State class. Here is the basic setup:

    // widget class
    class MyWidget extends StatefulWidget {
      @override
      _MyWidgetState createState() => _MyWidgetState();
    }

    // state class
    class _MyWidgetState extends State<MyWidget> {
      @override
      Widget build(BuildContext context) {
        return ...; // widget layout
      }
    }

Notice that

  • the widget class has a createState() method that returns the State. The State class has a build() method that builds the widget.
  • the _ underscore at the beginning of the name _MyWidgetState makes it private. It can only be seen within this file. This is a characteristic of the Dart language.

Responsive widgets

Now that we’ve talked about state, we’re ready to use it to make our widgets respond to user input.

Buttons

Replace the code in your main.dart file with the following code:

    import 'package:flutter/material.dart';

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

    // boilerplate code
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter',
          home: Scaffold(
            appBar: AppBar(
              title: Text('Flutter'),
            ),
            body: MyWidget(),
          ),
        );
      }
    }

    // widget class
    class MyWidget extends StatefulWidget {
      @override
      _MyWidgetState createState() => _MyWidgetState();
    }

    // state class
    // We will replace this class in each of the examples below
    class _MyWidgetState extends State<MyWidget> {

      // state variable
      String _textString = 'Hello world';

      // The State class must include this method, which builds the widget
      @override
      Widget build(BuildContext context) {
        return Column(
          children: [
            Text(
              _textString,
              style: TextStyle(fontSize: 30),
            ),
            RaisedButton( //                         <--- Button
              child: Text('Button'),
              onPressed: () {
                _doSomething();
              },
            ),
          ],
        );
      }

      // this private method is run whenever the button is pressed
      void _doSomething() {
        // Using the callback State.setState() is the only way to get the build
        // method to rerun with the updated state value.
        setState(() {
          _textString = 'Hello Flutter';
        });
      }
    }

Run the code that you pasted in above. It should look the same as our original layout, but now the first time we press the button, the text gets updated.

Notes:

  • The RaisedButton widget has an onPressed parameter where you can add a function that will be called whenever the button is pressed.
  • You have to update variables inside the setState() method if you want the changes to be reflected in the UI.
  • Do a hot restart (instead of a hot reload) to reset the state to the initial values.

TextFields

In this example whenever a TextField is changed, the Text widget above it gets updated.

Replace the _MyWidgetState() class with the following code:

    class _MyWidgetState extends State<MyWidget> {

      String _textString = 'Hello world';

      @override
      Widget build(BuildContext context) {
        return Column(
          children: [
            Text(
              _textString,
              style: TextStyle(fontSize: 30),
            ),
            TextField( //                       <--- TextField
              onChanged: (text) {
                _doSomething(text);
              },
            )
          ],
        );
      }

      void _doSomething(String text) {
        setState(() {
          _textString = text;
        });
      }
    }

Notes:

  • TextField has an onChanged parameter for a callback method. This method provides the current string after a change has been made.
  • If you want to get the text value without listening to onChanged, you can set the TextField’s controller parameter. See this post.

Checkboxes

For a checkbox with a label you can use a CheckboxListTile.

Replace the _MyWidgetState() class with the following code:

    class _MyWidgetState extends State<MyWidget> {

      bool _checkedValue = false;

      @override
      Widget build(BuildContext context) {
        return CheckboxListTile( //                   <--- CheckboxListTile
          title: Text('this is my title'),
          value: _checkedValue,
          onChanged: (newValue) {
            _doSomething(newValue);
          },
          // setting the controlAffinity to leading makes the checkbox come 
          // before the title instead of after it
          controlAffinity: ListTileControlAffinity.leading,
        );
      }

      void _doSomething(bool isChecked) {
        setState(() {
          _checkedValue = isChecked;
        });
      }
    }

Notes:

  • If you want to create a custom checkbox then you can use the Checkbox widget. It doesn't have a title included.
  • Try commenting out the controlAffinity line to see how that affects the layout. See this post also.
  • Here is an example of a list of checkboxes.

Dialogs

There are a few kinds of dialogs in Flutter, but let's looks at a common one: the AlertDialog. It's not difficult to set up.

Replace the _MyWidgetState() class with the following code:

    class _MyWidgetState extends State<MyWidget> {

      @override
      Widget build(BuildContext context) {
        return RaisedButton(
          child: Text('Button'),
          onPressed: () {
            _showAlertDialog();
          },
        );
      }

      void _showAlertDialog() {

        // set up the button
        Widget okButton = FlatButton(
          child: Text("OK"),
          onPressed: () {
            // This closes the dialog. `context` means the BuildContext, which is
            // available by default inside of a State object. If you are working
            // with an AlertDialog in a StatelessWidget, then you would need to
            // pass a reference to the BuildContext.
            Navigator.pop(context);
          },
        );

        // set up the AlertDialog
        AlertDialog alert = AlertDialog(
          title: Text("Dialog title"),
          content: Text("This is a Flutter AlertDialog."),
          actions: [
            okButton,
          ],
        );

        // show the dialog
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return alert;
          },
        );

      }
    }

Notes:

  • An AlertDialog needs the BuildContext. This is passed into the build() method and is also a property of the State object.
  • The Navigator is used to close the dialog. We will look more at navigators shortly.

Try a little more:

  • Can you make two buttons?
  • Three buttons?
  • See this post for the answer.

Gesture detectors

In the examples above we’ve seen how to respond to user input using some of the common widgets that are available. These widgets provide callback properties like onPressed and onChanged. Other widgets (like Text or Container) don't have a built in way to interact with them. Flutter gives us an easy way to make them interactive, though. All you have to do is wrap any widget with a GestureDetector, which is itself a widget.

For example, here is a Text widget wrapped with a GestureDetector widget.

    GestureDetector(
      child: Text('Hello world'),
      onTap: () {
        // do something
      },
    );

When the text is tapped, the onTap callback will be run. Super easy, isn't it?

You can try it. Every time you tap the text, the color changes.

Add import 'dart:math'; to your main.dart file and replace the _MyWidgetState() class with the following code:

    class _MyWidgetState extends State<MyWidget> {

      Color textColor = Colors.black;

      @override
      Widget build(BuildContext context) {
        return GestureDetector(  //                  <--- GestureDetector
          child: Text(
            'Hello world',
            style: TextStyle(
              fontSize: 30,
              color: textColor,
            ),
          ),
          onTap: () {  //                            <--- onTap
            _doSomething();
          },
        );
      }

      void _doSomething() {
        setState(() {
          // have to import 'dart:math' in order to use Random()
          int randomHexColor = Random().nextInt(0xFFFFFF);
          int opaqueColor = 0xFF000000 + randomHexColor;
          textColor = Color(opaqueColor);
        });
      }
    }

You are not limited to detecting a tap. There tons of other gestures that are just as easy to detect. Replace onTap in the code above with a few of them. See how the gestures are detected.

  • onDoubleTap
  • onLongPress
  • onLongPressUp
  • onPanDown
  • onPanStart
  • onPanUpdate
  • onPanEnd
  • onPanCancel
  • onScaleStart
  • onScaleUpdate
  • onScaleEnd
  • onTap
  • onTapDown
  • onTapUp
  • onTapCancel
  • onHorizontalDragDown
  • onHorizontalDragUpdate
  • onHorizontalDragEnd
  • onHorizontalDragCancel
  • onVerticalDragStart
  • onVerticalDragDown
  • onVerticalDragUpdate
  • onVerticalDragEnd
  • onVerticalDragCancel

A lesson about responding to user input wouldn't be complete without talking about navigation. How do we go to a different screen in Flutter? And once there, how do we go back?

Well, as you might expect, a new screen in Flutter is just a new widget. The way to get to these widgets is called a route, and Flutter uses a class called a Navigator to manage the routes. To show a new screen, you use the Navigator to push a route onto a stack. To dismiss a screen and go back to the previous screen, you pop the route off the top of the stack.

Here is how you would navigate to a new widget called SecondScreen.

    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SecondScreen(),
        ));

The context is the BuildContext of the current widget that is wanting to navigate to the new screen. The MaterialPageRoute is what creates the route to the new screen. And Navigator.push means that we are adding the route to the stack.

Here is how you would return from the SecondScreen back to the first one.

    Navigator.pop(context);

Does that look familiar? Yes, we already used that same code to dismiss the AlertDialog that we made before.

Try it out yourself. Here is what it will look like on the iOS simulator.

Replace all of the code in main.dart with the following code.

    import 'package:flutter/material.dart';

    void main() {
      runApp(MaterialApp(
        title: 'Flutter',
        home: FirstScreen(),
      ));
    }

    class FirstScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('First screen')),
          body: Center(
            child: RaisedButton(
              child: Text(
                'Go to second screen',
                style: TextStyle(fontSize: 24),
              ),
              onPressed: () {
                _navigateToSecondScreen(context);
              },
            )
          ),
        );
      }

      void _navigateToSecondScreen(BuildContext context) {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => SecondScreen(),
            ));
      }
    }

    class SecondScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Second screen')),
          body: Center(
            child: RaisedButton(
              child: Text(
                'Go back to first screen',
                style: TextStyle(fontSize: 24),
              ),
              onPressed: () {
                _goBackToFirstScreen(context);
              },
            ),
          ),
        );
      }

      void _goBackToFirstScreen(BuildContext context) {
        Navigator.pop(context);
      }
    }

Passing data forward

Sometimes you need to send data to the new screen that you are displaying. This is easy to do by passing it in as a parameter in the SecondScreen widget's constructor.

    class SecondScreen extends StatelessWidget {
      final String text;
      SecondScreen({Key key, @required this.text}) : super(key: key);

The Dart constructor syntax may look a little strange to you. Here is a brief explanation:

  • The comma separated items between the { } braces are the named parameters. They're optional, but users will be warned if they don't provide an @required parameter.
  • In Flutter a Key is used to differentiate widgets in the widget tree. See this video for more.
  • The this. prefix is used for variables that are defined in the current class.
  • The part after the : colon is a comma separated initialization list. The lines in this list are run before the super class's constructor. In this case there is nothing here except a call to a specific constructor of the super class.
  • See the answers to this Stack Overflow question for more about constructors.

Now that the constructor is set up, you can pass in data when you call it from the FirstScreen.

    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SecondScreen(text: 'Hello',),
        ));
  • Note the text "Hello" being passed in as a parameter.

You can find the full code for the example here.

Passing data back

At other times you need to send data back to the previous screen. Flutter does this in an interesting way.

  • The first screen starts the second screen and then waits for a result, which it can use after the second screen finishes. You will notice the async and await keywords below. Dart makes it easy to do things that you have to wait for (like web requests or long running tasks). Read this for more information. It’s way easier than Android AsyncTasks!
      void startSecondScreen(BuildContext context) async {

        // start the SecondScreen and wait for it to finish with a result
        final result = await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => SecondScreen(),
            ));

        // after the SecondScreen result comes back, update the Text widget with it
        setState(() {
          text = result;
        });

      }
  • In the second screen you pass the data back by supplying it as a parameter in the pop method.
    Navigator.pop(context, 'How are you?');

You can find the full code for the example here.

Conclusion

In this lesson we have gone from static layouts to dynamic ones with widgets that respond to user input. Making responsive widgets like this means that we need to deal with things that change, whether it's text, color, size, or any number of other things that affect the UI. The value of these variables is known as the state, and widgets that have state are known as StatefulWidgets.

Properly managing state in Flutter is a big topic. You have already seen two ways to do it in this lesson. One was having a method variable in the State class. It was available to all of the widgets throughout the class. As the complexity increases, though, it is not practical to include the entire layout in a single build() method, nor is it good practice to allow global variables.

Another way we managed state in this lesson was passing data as a parameter into another widget. This works great when one widget is directly calling another, but it can get cumbersome when you need the state from another widget somewhere far away in the widget tree.

As you continue to study you will hear about topics like inherited widgets, Streams, BLoC, and Redux. They are things that you should learn about eventually, but don't worry about them right now. I like what Hillel Coren said:

My approach when working with a new technology is to start with the simplest implementation and only add in extras once I’ve felt the pain they’re designed to eliminate.

You already know enough now to begin making Flutter apps. You can deal with the difficulties as they come. So take that app design that you've got in your head and start creating it! You’re ready to go!

This concludes our First Steps with Flutter series. You can find the code for this tutorial on GitHub.

Further study

Clone the project repository
  • Flutter
  • Android
  • iOS
  • no pusher tech

Products

  • Channels
  • Chatkit
  • Beams

© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.