Flutter Learning Guide: write the first application and explain it by Tencent T3


This is a series of articles, and there are many later articles. I hope they can be helpful to you.

Fluent is a mobile end cross platform development framework launched by Google, and the programming language used is Dart. From React Native to fluent, developers have never stopped exploring cross platform solutions. After all, it can save us half of the manpower on the mobile terminal. In this article, we will understand his development process by writing a simple Flutter.

The demo we want to develop here is very simple. Just put a button in the middle of the screen. When you click it, simulate shaking two dice and pop up the window to display the results. Let's roll up our sleeves and work.

Create project

We assume here that the reader has installed Flutter and developed using Android Studio with the Flutter plug-in installed. If you haven't configured the development environment, you can refer to Yugang's This article.

Let's start creating the project:

  1. Select File > New > New shutter project
  2. In the selection panel that pops up next, select shutter application
  3. Fill in the basic information of the application here. Project name let's write fluent_ Demo is ready. Note that the project name must be a legal Dart package name (lowercase + underscore, and can have numbers). After filling in, click next and finish.

When you first create a project, it takes a little longer to download gradle.

Write code (1)

The project we created in the previous section already has some code. Interested readers can go to their mobile phones and have a look. The relevant code is in lib/main.dart.

In order to experience the process of developing an application from scratch, we first delete the contents in lib/main.dart.

First, create a main function. Like other languages, the main function is an application entry:

void main() {
}

Let's write a Widget as our app. In fluent, everything is a Widget.

import 'package:flutter/material.dart';
void main() {  
//  Create a   MyApp
  runApp(MyApp());
}
///   this   widget   At the top of this application   widget.
///
///   this   widget   Is stateless, so what we inherit is  [ StatelessWidget].
///   Corresponding, stateful   widget   Can inherit  [ StatefulWidget]
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) { 
   //  Create content
  }
}

Now let's get to the point, implement a button, and pop up the box to display the results when clicking:

@override
Widget build(BuildContext context) {
  //  We want to use   material   Application of style, so it is used here   MaterialApp
  return MaterialApp(
    //  Mobile devices use this   title   To represent our application. Specifically, in   Android   In the device, we click
    //  recent   This button is displayed when you open the recent applications list   title. 
    title: 'Our first Flutter app',
    //  App's home page  
   home: Scaffold(
      appBar: AppBar(
        title: Text('Flutter rolling demo'), 
     ), 
     //  We know, Flutter   Everything in the is   widget.  To put the button in the center of the screen,
      //  Used here   Center (it is a   widget). 
      body: Center( 
       child: RaisedButton(  
        //  Called when the user clicks
          onPressed: _onPressed, 
         child: Text('roll'),
        ),
      ),
    ),
  );
}
void _onPressed() {
  // TODO
}

Installation and commissioning (1)

Now, click Run to run our first fluent application. If there is no accident, you will see the following page:

If you encounter any difficulties, you can check tag first_ app_ Code of step1:

git clone https://github.com/Jekton/flutter_demo.git
cd flutter_demo
git checkout first_app_step1

Since this is the first time to write a fluent application, we are not so confident that the above code can be executed as expected, so let's make a log to confirm whether onPress will be executed after clicking the button.

You can use the print provided by Dart to log, but when there are many logs, the print output may be discarded by Android. debugPrint will be a better choice at this time. The corresponding log information can be viewed in the Dart Console (view - > tool, windows - > run or open with Command+4 on Mac).

void _onPressed() {
  debugPrint('_onPressed');
}

After saving (automatic Hot Reload), we click the button again and print the following information on my device:

I/flutter (11297): _onPressed
V/AudioManager(11297): playSoundEffect   effectType: 0
V/AudioManager(11297): querySoundEffectsEnabled...

The first line here is our fight. Now we are confident enough to say that after clicking the button, it will be executed_ The onPressed method.

Write code (2)

Software development is usually a spiral process, which can not be completed through one-time coding and debugging. Now, let's start the second iteration.

The next thing to do is to_ A box pops up in onPressed:

//  context   What is used here is   MyApp.build   Parameters of
void _onPressed(BuildContext context) {
  debugPrint('_onPressed');
  showDialog(
    context: context,
    builder: (_) {
      return AlertDialog(
        content: Text('AlertDialog'),
      );
    }
  );
}

Unfortunately, this time was not so smooth. Dialog does not pop up, and the following problem is reported:

I/flutter (11297): Navigator operation requested with a context that does not include a Navigator.
I/flutter (11297): The context used to push or pop routes from the Navigator must be that of a widget that is a
I/flutter (11297): descendant of a Navigator widget.

The reason is that the widget of status can only be used to display information and cannot have other actions. So, it's time for StatefulWidget to play.

class RollingButton extends StatefulWidget {
  //  StatefulWidget   You need to implement this method and return a   State
  @override
  State createState() {
    return _RollingState();
  }
}
//  It may seem a little disgusting. The generic parameter here is   RollingButton
class _RollingState extends State<RollingButton> {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('Roll'),
      onPressed: _onPressed,
    );
  }
  void _onPressed() {
    debugPrint('_RollingState._onPressed');
    showDialog(
        //  first   context   Is the parameter name, the second   context   yes   State   Member variables for
        context: context,
        builder: (_) {
          return AlertDialog(
            content: Text('AlertDialog'),
          );
        }
    );
  }
}

To implement a stateful widget, you can inherit the StatefulWidget and return a State in the createState method. Except for this part, the code is not much different from what we wrote before.

The rest is to replace the buttons used in MyApp. The modified code is as follows:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Our first Flutter app',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter rolling demo'),
        ),
        body: Center(
          child: RollingButton(),
        ),
      ),
    );
  }
}

Run again and click the button, we will see the dream dialog.

If you are in trouble, you can check tag first_ app_ The code of step 2.

Finally, let's implement "roll":

import 'dart:math';
class _RollingState extends State<RollingButton> {
  final _random = Random();
  // ...
Picture transfer in progress...(img-iPQf2rFe-1630928216037)]

If you are in trouble, you can check it out tag first_app_step2 Code for.

Finally, let's realize“ roll": 

import 'dart:math';
class _RollingState extends State {
  final _random = Random();
  // ...

Tags: iOS Android Design Pattern Flutter

Posted on Mon, 06 Sep 2021 19:31:51 -0400 by cbolson