preface

With the basic development environment configured, this article will go straight to the topic and implement a simple login page. Enter a username and password and click login to verify the validity of the input, simulate an API login, and finally pop up a message indicating that the login was successful.

The sample code is inHere making.

Tips: Before you start, you should quickly learn the basic syntax of dart

layout

This example is a fairly common simple app page, with a navigation bar and title at the top, a white page, a picture display control from top to bottom, a text input control for user name and password, and a submit button.

layout

Before starting a Flutter layout, one should always keep in mind that all that a Flutter layout displays are widgets, including visible pages, images, input fields, buttons… Other invisible Column layout controls (‘Column’), Container layout controls (‘Container’), (‘SizedBox’), user Form display controls (‘Form’), and even Padding controls (‘Padding’) and Center controls (‘Center’);

  • Start with the main function
void main() {
  debugPaintSizeEnabled = false;
  runApp(new LoginAlertDemoApp());
}

class LoginAlertDemoApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        title: 'Login Alert',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Scaffold(
          appBar: AppBar(
            title: Text('Login Alert'), ), body: new LoginHomePage(), )); }}Copy the code

The main function, as the name suggests, is the entry to the app. The debugPaintSizeEnabled function is displayed by the user. Then you call the SDK’s runApp method, pass in a Widget object and display it on the screen, so that Widget is the base Widget for the APP display, somewhat equivalent to the rootViewController in iOS development that hosts the display of the entire APP.

The Widget passed in the runApp method in this example is LoginAlertDemoApp, inherited from the StatelessWidget; Overrides its build method to create a Widget for the MaterialApp. In other words, the object mainly responsible for display is MaterialApp, which is a basic display Widget used to implement a set of Material Design design style designed by Google. It encapsulates a series of common components and navigation controls, such as theme control. That Scaffold is one of the basic components of Material Design that implements basic page layout structures such as the page navigation bar. That Scaffold also encapsulates a number of basic controls such as the ‘drawer page’, toast prompt, Bottom sheet prompt. Apps based on the Material Design style are basically built on top of these two basic controls.

Now we have our own page layout. LoginHomePage inherits from StatefulWidget. Notice that widgets are StatefulWidget and StatelessWidget. A StatefulWidget is a variable State Widget that requires a State to hold some State data during its life cycle and update the Widget with setState notifications when data changes. StatelessWidget, on the other hand, is stateless and simply displayed without maintaining its state.

So we need _LoginHomePageState to maintain some state change data in the LoginHomePage life cycle and build display widgets for LoginHomePage in real time using the build method.

The basic control

  • Form

Page analysis this is a simple Form submission page that can be laid out using the ‘Form’ and easily validated and prompted by input via the validate() method of its State property. Validate () calls TextFormField’s validator to perform validation.

  • Image

It is used to display images. Network images and local images are supported. Local images need to be added to the configuration file

# To add assets to your application, add an assets section, like this:
  # assets:
  # - images/a_dot_burr.jpeg
  # - images/a_dot_ham.jpeg
  assets:
    - images/lake.jpg
Copy the code
  • TextFormField

The corresponding text input control in the Form validator validates input and returns a string notification at the bottom of the input box if the validation fails.

  • RaisedButton

Button, nothing to say, onPressed to call back

  • Column

Column layout. The controls in this demo are arranged from top to bottom, and Column is a good fit.

  • Popup window

Call AlertDialog to display a text Widget.

Third-party Components

This demo uses a third-party load prompt component called Flutter_spinkit

The main.dart code at the top

import 'package:flutter_spinkit/flutter_spinkit.dart';
Copy the code

This is flutter_spinkit, a third-party load prompt component. Before using a third-party load prompt component, you need to add the dependency configuration to pubspec.yaml file:

flutter_spinkit: "^ 2.1.0." "
Copy the code

VSCode automatically executes ‘flutter packages get’ to download components after saving.

Use code:

final _loadingContainer = Container( constraints: BoxConstraints.expand(), color: Colors.black12, child: Center( child: Opacity(Opacity: 0.9, child: SpinKitWave(color: color.red, size: 50.0,),));Copy the code

Asynchronous operations

Click the button to execute the following code:

  void _toggleSubmit() {
    if (_formKey.currentState.validate()) {
      setState(() {
        _showLoading = true;
      });

      _loginRequest().then((onValue) {
        setState(() {
          _showLoading = false;
        });
        showDialog(
            context: context,
            builder: (context) {
              String alertText = 'login success! ' +
                  ' \nuserName:' +
                  _userNameTextController.text +
                  '\npassWord:' +
                  _passwordTextController.text;
              returnAlertDialog( content: Text(alertText), ); }); }); }}Copy the code
  • The hidden loading box is displayed

Use the GlobalKey’s currentState to retrieve the FormState, and then call validate() to validate the username and password input in the Form. Updating the _showLoading property to true or false with the setState() method re-executes the Build method, which dynamically shows and hides the loading box.

  • Asynchronous operations
Future _loginRequest() async {
  return Future.delayed(Duration(seconds: 3), () {
    //do nothing
    print('login success');
  });
}
Copy the code

The _loginRequest function returns a Future, which is used as a dart support keyword for asynchronous operations. As the name implies, this function will be called and executed in the Future, not immediately.

In the _loginRequest function, there is only a simple execution delay of 3 seconds to simulate the API call time. After clicking the Submit button, this method is called. After the execution of this method, then method is called to hide the loading box with setState, and a prompt box is displayed to show the obtained user name and password.

_loginRequest().then((onValue) {
      setState(() {
        _showLoading = false;
      });
      showDialog(
          context: context,
          builder: (context) {
            String alertText = 'login success! ' +
                ' \nuserName:' +
                _userNameTextController.text +
                '\npassWord:' +
                _passwordTextController.text;
            return AlertDialog(
              content: Text(alertText),
            );
          });
    });
    
Copy the code

Well, that’s it, it’s time for the next learning demo, which will continue to be updated…

reference

  • Official Documentation of Flutter
  • Flutter Practice 5: The use of asynchronous Async, await and Future