Note: This article is republished from the personal public number (Island front island)

Flutter is Google’s mobile UI framework for quickly building high quality native user interfaces and applications for mobile (iOS & Android), Web, desktop, and embedded devices from a single code base.


  • 原 文 : The foundation of Flutter Hello World

In the last article, we focused on how the simple Hello World was implemented. So this time I’m going to talk about the two forms of components.

But before I do that, I think it’s worth saying a few things briefly about the Dart language.

On the Dart

Dart is a web programming language developed by Google and released on October 10, 2011. Dart is a small compiled language.

Dart supports and targets development requirements for three different platforms:

  • Dart WebDev develops browser applications.
  • Flutter develops mobile applications.
  • Dart VM development scripts or server applications.

The characteristics of the Dart

Dart incorporates some of the features of both back-end and front-end languages. Everything in Dart is an object, function is an object; String is an object; Number is an object; Null is also an object. (Does it smell inside?)

  • This is a strongly typed language that can do type inference.
  • All data types are derived from Object.
  • If the variables are not initialized, the default values are null.
  • You have dynamic typing, generics, and operator overloading.
  • Have the top-level function main.
  • No declaration type keyword”public“”private“To”_“Indicates that it is only valid for the current domain and is private.
  • Final a single declaration, even if only one assignment can be made and subsequent assignments are invalid.

Ok, that’s a brief introduction to the Dart language. For more information about the Dart language, see dart.dev/

State X Widget inheritance relationship

After a brief introduction to the Dart language, it’s time to talk about statelessWidgets and StatefulWidgets. As mentioned in the previous article, statelessWidgets and StatefulWidgets both inherit from widgets and are abstract classes of widgets. 【 Portal 】



(Inheritance relationship of StatelessWidget)



(Inheritance relationship of StatefulWidget)

From the source code, we can see and confirm that statelessWidgets and StatefulWidgets both inherit from widgets and are abstract classes of widgets.

Here I have put their relationship in order.



(Inheritance diagram for StatelessWidget and StatefulWidget)

As shown in the figure, this confirms that all objects in Dart are Objects.

I also mentioned statelessWidgets and StatefulWidgets in previous articles, although they are abstract classes of widgets. However, they are different in that they are used to implement Widget components used in different scenarios.

State X Widget stateful and stateless

StatelessWidget – Stateless

The StatelessWidget is stateless, meaning it cannot be updated through data changes.

So, let’s implement a little 🌰, and you’ll know.

The project is still our MyApp, and we’ll implement a class called UnchangeWidget that inherits from the StatelessWidget.

Let’s implement a button that updates our text content by clicking the button.

// Inheriting the StatelessWidget means that the content cannot be changed through data changes
class UnchangeWidget extends StatelessWidget {
  String setText = 'I am the original text'; // Declare variable literal - default value

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      children: <Widget>[
        Text(setText), // Use the variable setText to set the contents of Text
        RaisedButton(
          child: Text('Change content'),
          onPressed: () { // Button click events - change the content
            print('Button triggered');
            setText = 'I am the new word'; // Assign new text content},)],)); }}Copy the code

The results are as follows:



(The text has not been updated)

Even though the button is triggered and the setText is assigned, our Text content is not updated.

StatefulWidget – Stateful

Statefulwidgets are stateful, meaning they can be updated with data changes, and you need setState to manage state.

Ok, so let’s rewrite the UnchangeWidget again to inherit from the StatefulWidget.

Here you can rewrite the code with the editor’s quick fix feature.

// Inheriting StatefulWidget means that the content can be changed through data changes
class UnchangeWidget extends StatefulWidget {
  String setText = 'Original content'; // Variable set text - default value

  @override // Create a shorthand for the state control class, where new can also be omitted
  _UnchangeWidgetState createState() => _UnchangeWidgetState();
}

class _UnchangeWidgetState extends State<UnchangeWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(children: <Widget>[
        Text(widget.setText), // Use the variable setText to set the contents of Text
        RaisedButton(
          child: Text('Change content'),
          onPressed: () { // Button click events - change the content
            print('Button triggered');
            setState(() { // Call the state change function
              widget.setText = 'I am the new word'; // Assign new text content
              print('Status change text update'); }); },),),); }}Copy the code

The results are as follows:



(Update content with setState)

Here we can see from the result that the state is updated by the button trigger call setState to update the Text content.

doubt

Some kids don’t like it: “StatefulWidget uses setState to update content, StatelessWidget doesn’t, unfair!”

Ha ha ha ha, it doesn’t matter, then let’s give it a try! I like you when you’re not afraid to make a difference.

We will now continue with the code for the StatefulWidget and update the inherited object directly to the StatelessWidget.

(Change the inheritance type to StatelessWidget)

So let’s see what happens? Type R on the command line and wait patiently…

Come on, let’s give a round of applause to these brave young men.

Why is that?

Why is that? Because they are implemented differently in the source code.



(StatelessWidget source section)





(StatefulWidget source section)

Statelesswidgets and StatefulWidgets are implemented differently in the source code.

I can translate that very briefly.

StatelessWidget parts:

The implementation of this method must rely only on:

  • Fields of widgets, which themselves cannot change over time, and any state used from the [context] environment.

If the widget’s [build] method depends on something else, use [StatefulWidget] instead.

StatefulWidget parts:

Subclasses should override this method to return an instance of their associated newly created [State] subclass. (1) When building widgets, you can get state information synchronously. (2) During the widget’s life cycle, the widget implementation needs to ensure that [state.setState] is used to notify [State] of the information that needs to be changed when the State changes.

Therefore, StatelessWidget does not participate in component life State management or associated operations on State, while StatefulWidget does participate in State rewriting. The user is also required to rewrite createState to ensure the association with State.

That is, use the StatefulWidget if you want to implement a dynamic, updatable data component, or use the StatelessWidget if you just want to display static text information or content.


conclusion

  • When you don’t quite understand, try to test your ideas.
  • Sometimes consider looking at the source code. Some good programming languages or open source frameworks have good comments in the source code section that tell you what they do there.