• Mdc-101: Material Components (MDC) of a Flutter
  • The original author: codelabs.developers.google.com
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: DevMcryYu

Mdc-101: Material Components of A Flutter

  • Mdc-101: Material Components of A Flutter
  • MDC 102 Flutter: Material structure and layout
  • MDC 103 Flutter: Material Theming color, shape, height and type
  • MDC 104 Flutter: Material Advanced Components

1. Introduction

What is Material Design and Material Components for Flutter?

Material Design is a system for building eye-catching, aesthetically pleasing digital products. By combining style, branding, interaction, and movement under a single set of principles and components, product teams unlock their greatest design potential.

Material Components for Flutter (MDC-Flutter) combines design and engineering with a library of Components to create a unified user experience across a variety of applications and platforms. As the Material Design system evolved, these components were updated to ensure a uniform pixel-level perfect implementation, following Google’s front-end development standards. MDC is also available on Android, iOS, and the Web.

In this tutorial, you will use multiple MDC Flutter components to build a landing page.

You’re going to build one

This tutorial is the first of four that will guide you through building an e-commerce app called Shrine, which sells clothing and home items. It will demonstrate how to use MDC-FLUTTER custom components to embody any brand and style.

In this tutorial, you will build a landing page for Shrine that contains the following:

  • Logo of a Shrine
  • Application Name (Shrine)
  • Two text boxes, one for user name and one for password
  • Two buttons, one for ‘Cancel’ and one for ‘Next’

Tutorials can be found at:

  • MDC 102 Flutter: Material structure and layout
  • MDC 103 Flutter: Material Theming color, shape, height and type
  • MDC 104 Flutter: Material Advanced Components

At the end of MDC-104, you will build an application like this:

The MDC components used in this tutorial

  • Text field
  • Button
  • Ripple

In this tutorial, you will use the default components provided by MDC-FLUTTER. You will learn how to customize them in MDC 103 Flutter: Material Theming’s colors, shapes, heights and types.

2. Install the Flutter environment

The premise condition

To start developing mobile apps with Flutter, you need to:

  • Flutter SDK
  • IntelliJ IDE with the Flutter plugin, or your favorite code editor

Flutter’s IDE tools are available for Android Studio, IntelliJ IDEA Community (free) and IntelliJ IDEA Ultimate.


  • A computer running macOS
  • Xcode 9 or later
  • IOS emulators, or iOS physical devices


  • A computer running macOS, Windows, or Linux
  • Android Studio
  • Android emulator (shipped with Android Studio) or Android physical device

Get detailed Flutter installation information

Important: If the Allow USB Debugging dialog box appears on your Android phone connected to your computer, enable the Always Allow from this computer option, and then click OK.

Before continuing with this tutorial, make sure your SDK is in the right state. If Flutter has been installed before, use Flutter Upgrade to ensure that the SDK is up to date.

flutter upgrade
Copy the code

Running flutter Upgrade will automatically run flutter Doctor. If this is the first time that a Flutter is installed and no upgrade is required, run the Flutter Doctor manually. View all check marks displayed; This will download any missing SDK files you need and make sure your computer is properly configured to develop Flutter.

flutter doctor
Copy the code

3. Download the tutorial starter application

Download the initial program

This starter program is located in the material- Components -flutter-codelabs-101-starter/ MDC_100_series directory.

. Or clone it from GitHub

To clone this project from GitHub, run the following command:

git clone https://github.com/material-components/material-components-flutter-codelabs.git
cd material-components-flutter-codelabs
git checkout 101-starter
Copy the code

More help: Clone the repository from GitHub

Right branch

Tutorial MDC-101 to 104 continuous build. So when you finish the 101 code, it will become the initial code for the 102 tutorial! The code is divided into different branches, and you can list them all using the following command:

git branch --list

To see the complete code, switch to the branch 102-starter_and_101-complete.

Build your project

The default for the following steps is Android Studio (IntelliJ).

Create a project

  1. In terminal, navigate to the Material – Components -flutter- Codelabs

  2. Run the FLUTTER create MDC_100_series

Open the project

  1. Open Android Studio.

  2. If you see the welcome page, click to open your existing Android Studio project.

  1. Navigate to thematerial-components-flutter-codelabs/mdc_100_seriesDirectory and click Open, which will open the project.

You can ignore any errors you see in the analysis until you build the project once.

  1. In the project panel on the left, delete the test file../test/widget_test.dart

  1. If prompted, install all platforms and plugin updates or FlutterRunConfigurationType, and then restart the Android Studio.

Tip: Make sure you have the Flutter and Dart plug-ins installed.

Run the initial program

The following steps are performed by default on an Android emulator or device. You can also do this on an iOS emulator or device, as long as you have Xcode installed.

  1. Select device or emulator.

If the Android emulator is not already running, choose Tools -> Android -> AVD Manager to create your device and start the emulator. If the AVD already exists, you can start the emulator directly from IntelliJ’s device selector, as shown in the next step.

(For iOS emulators, if it is not already running, start it on your development Device by selecting Flutter Device Selection -> Open iOS Simulator.)

  1. Start Flutter application:
  • Look for the Flutter Device Selection drop-down menu at the top of your editor window and select the Device (for example, iPhone SE/Android SDK Built for).
  • Click on therunIcon (

    ).

If you cannot run the application successfully, stop to resolve your development environment issues. Try to navigate to the Material – Components -flutter-codelabs; If you download the.zip file in terminal, navigate to the material-components-flutter-codelabs-… Then run the FLUTTER create MDC_100_series.

Success! The initial login code for Shrine should now be running in your emulator. You can see the logo of Shrine and the name “Shrine” underneath it.

If you see any warnings that PubSpec has been edited, ignore them. When you press the Run button, it runs flutter Packages get for you!

The flutter Packages get will install the dependencies listed in your pubspec.yaml file. You can write your own packages to publish on Pub. This tutorial series uses the shrine_images custom package to display the product images you will see in MDC-102.

The FLUTTER Packages GET calls the underlying Dart Pub package manager to install all the dependencies of the FLUTTER application. The product images in this series use the custom shrine_images package.

For more information about packages, see Using Packages.

Let’s look at the code.

login.dartWidgets in

Open the login. The dart. It should contain:

import 'package:flutter/material.dart'; class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> {// TODO: add text editing controller (101) @override Widget build(BuildContext context) {returnScaffold(body: SafeArea(Child: ListView(padding: EdgeInsets. Symmetric (Horizontal: 24.0)), children: <Widget>[SizedBox(height: 80.0), Column(children: <Widget>[image.asset ('assets/diamond.png'), SizedBox (height: 16.0), the Text ('SHRINE'), ], ), SizedBox(height: // TODO: delete padding: true (103) // TODO: // TODO: Add textbox widget (101) // TODO: Add button bar (101)],),),); } // TODO: add AccentColorOverride (103)Copy the code

Note that it contains an import statement and two new classes:

  • importThe statement introduces the Material Components into this file
  • LoginPageClass represents the entire page displayed in the emulator.
  • _LoginPageStateOf the classbuild()Function controls how all widgets in the UI are created.

To learn more about the basics of the Flutter UI and what a Widget is, you can visit the Flutter Widget framework or try writing your first Flutter application, Part 1.

4. Add text box widgets

First, we’ll add two text fields to the landing page where the user can enter a username and password. We’ll use the textbox widget that displays a floating label and activates the ripple effect of the touch.

The Material text box has been greatly enhanced to improve brand flexibility; Improvements are supported by extensive user experience (UX) research to achieve better visual design and improved usability.

Learn more about the new TextField in the Material Guidelines article.

This page consists mainly of a ListView, which arranges its children in a scrollable column. Let’s put the text box at the bottom.

Add a text box widget

Add two new text boxes and an interval (spacer) after the SizedBox(height: 120.0).

// TODO: Add text box widget (101) // [username] TextField(decoration: InputDecoration(filled:true,
    labelText: 'Username',),), // spacer SizedBox(height: 12.0), // [password] TextField(decoration: InputDecoration(filled:true,
    labelText: 'Password',
  ),
  obscureText: true,),Copy the code

Each text box has an decoration:, which has an InputDecoration widget. Filled: True means that the background of the text box is filled with light colors to help people identify the click or touch areas of the text box. The obscureText: true value of the second text box automatically replaces the user’s input with a dotted form, which applies to where the password is entered.

Save your project (use the shortcut: Command/CTRL + S) to perform a hot reload.

You should now see a page with a useful username and password text box! View floating labels and ink ripple animation effects:

If the application is not updated, click Run again, or click Stop and then click Run.

The functions of the text box include:

  • You can easily change the look of the TextField widget. In the area you want to decorate, specify the value of InputDecoration.
  • The MDC text box displays touch feedback (called MDC ripple or “ink”) by default.
  • FormField is a similar widget with special capabilities to embed fields in Forms.
  • TextField class document

5. Add a button

Next, we will add “Cancel” and “Next” buttons to the login page. We will use two MDC Button widgets: FlatButton (referred to as “Text Button” in Material Guidelines) and RaisedButton (referred to as “Contained Button”).

Choose between a Text Button and a Contained Button

Why not simply display two Contained buttons? This is because the type of each button indicates which actions are more important than others.

A layout should contain a prominent button. This clearly shows that the other buttons are less important. The highlighted button represents the actions we most want users to take to advance our application.

The last thing we like a user to do is cancel login. Because the Contained Button catches the eye with its raised style, it should be used for more important operations. The plain text button on the left looks less conspicuous by comparison.

Learn more about the button hierarchy in the Material Guidelines button section.

Add button bar

Below the textbox, add ButtonBar as a child of the ListView:

// TODO: add button (101) ButtonBar(// TODO: Add beslope rectangle to CANCEL (103) children: <Widget>[// TODO: add button (101)],Copy the code

ButtonBar aligns all of its children horizontally

Add a button

Then add two buttons to the Children list of ButtonBar:

// TODO: Add button (101) FlatButton(child: Text('CANCEL'), onPressed: () {// TODO: Clear Text box (101)},), // TODO: Add height to NEXT button (103) // TODO: Add bevelled rectangle to NEXT (103) RaisedButton(child: Text()'NEXT'), onPressed: () {// TODO: Display next page (101)},),Copy the code

Why is our onPressed: field an empty block?

If we pass NULL, or if the field is not included (the default is NULL), the button will be disabled. Without feedback about touch, we can’t get a good idea of their enabling behavior. Using empty blocks prevents them from being disabled.

For more information about buttons and their interactions, see Adding interactions to your application.

Save your project. In the bottom text box, you should see two buttons:

ButtonBar handles the layout work for you. It positions the buttons horizontally so that they are adjacent to each other based on the padding in the current ButtonTheme. (You’ll learn more about this in MDC-103.)

Touching the button initiates the ink ripple animation and causes nothing else to happen. Let’s add functionality in the anonymous function onPressed: to make the cancel button clear the text box and close the screen with the next button:

Add TextEditingControllers

To be able to clear the text field values, we will add TextEditingControllers to control their text.

Add the controller as a final variable under the declaration of the _LoginPageState class.

// TODO: Add text edit controller (101) final _usernameController = TextEditingController(); final _passwordController = TextEditingController();Copy the code

In controller: of the first textbox, set _usernameController:

// [username] TextField(controller: _usernameController,Copy the code

In controller: of the second textbox, set _passwordController:

// [password] TextField(controller: _passwordController,Copy the code

Edit onPressed

Add the command to clear each controller in the FlatButton’s onPressed: function:

// TODO: Clear the text box (101) _userNamecontroller.clear (); _passwordController.clear();Copy the code

Save your project. Now when you type something into a text box, pressing the Cancel button will clear each text box.

This landing page is in good condition! Let’s take the user to the rest of the Shrine application.

The pop-up

To cancel this view, we want to pop up (or delete) the page (called route in Flutter) from the navigation stack.

Navigator is responsible for maintaining a routing stack, just like the UINavigationController on iOS. Pushing a route puts it at the top of the stack. Unstack deletes the recently added route. Dart in our program, call initialRoute: ‘/login’, add the login screen to the Navigator, and place it on top of what entered home:.

Learn more about routing and navigation in navigation basics.

In the RaisedButton onPressed: function, eject the latest route from the Navigator:

// TODO: display next page RaisedButton(child: Text('NEXT'), onPressed: () { Navigator.pop(context); },),Copy the code

That’s it! Save the project. Then click Next.

You did it!

This page is the starting point for our next tutorial, and you can continue using it in MDC-102.

About buttons:

  • In addition to FlatButton and RaisedButton, there are OutlineButton, FloatingActionButton, IconButton, etc.
  • Browse for buttons and their documentation in the MDC Widgets directory.

6. All done

We added text boxes and buttons and barely had to worry about layout code. The Material Components for Flutter have many styles and can be arranged almost effortlessly.

The completed MDC-101 application can be found in the 102-starter_AND_101-complete branch.

You can test your own version of the app against the apps in that branch.

The next step

Text boxes and buttons are two of the core components of the Material system, but there’s more! You can browse the rest of the Flutter widgets in the Material Components library.

Also, go to MDC-102 Flutter: Material Structure and Layout to learn about the Flutter components covered by MDC-102.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.