Flying from scratch: statelesswidget

Time:2021-2-23

Flying from scratch: statelesswidget

This time, we will show what is the widget of flutter, that is, the widget; and how to use stateless widget, that is, stateless widget in flutter.

As for flutter, developers can use a simple set of code to build Android and IOS applications at the same time.

characteristic

Widgets are the basic building blocks of the flutter application, each of which is an immutable declaration and part of the user interface. For example, button, text, color and padding used in layout.

Now let’s take a look at flutter_ An instance in GitHub.

Flying from scratch: statelesswidget

The selected item has only two information, head image and name. In order to avoid the repeated use of the code, we separate it into an independent widget. The specific code is as follows

class FollowersItemView extends StatelessWidget {
  final GestureTapCallback tapCallback;
  final String avatarUrl;
  final String name;
 
  const FollowersItemView(
      {Key key, this.avatarUrl, this.name, this.tapCallback})
      : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15.0),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: tapCallback,
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                FadeInImage.assetNetwork(
                  placeholder: 'images/app_welcome.png',
                  image: avatarUrl,
                  width: 80.0,
                  height: 80.0,
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: 15.0),
                    child: Text(
                      name,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      style: TextStyle(
                        color: Colors.grey[600],
                        fontSize: 20.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                )
              ],
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 15.0),
              child: Divider(
                thickness: 1.0,
                color: colorEAEAEA,
                height: 1.0,
                endIndent: 0.0,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

It inherits from statelesswidget. Statelesswidget is stateless and its data cannot be changed. This property is in line with the part we’re going to pull out. The extracted parts need to display the head image and name without any form of interaction. The only interaction is clicking, but it doesn’t involve data changes. So define the data as final type in the code. It’s essentially like a text part. It doesn’t change its internal properties over time, just like an input text part or an animated part.

Since there is no change, we can also define its constructor as const type.

With the above widget extraction, we can use the stateless widget directly in listview

  @override
  Widget createContentWidget() {
    return RefreshIndicator(
      onRefresh: vm.handlerRefresh,
      child: Scrollbar(
        child: ListView.builder(
            padding: EdgeInsets.only(top: 15.0),
            itemCount: vm.list?.length ?? 0,
            itemBuilder: (BuildContext context, int index) {
              final item = vm.list[index];
              return FollowersItemView(
                avatarUrl: item.avatar_url,
                name: item.login,
                tapCallback: () {
                  Navigator.push(context, MaterialPageRoute(builder: (_) {
                    return WebViewPage(title: item.login, url: item.html_url);
                  }));
                },
              );
            }),
      ),
    );
  }

You can refer to followitemview in listview and pass in unchanging data.

Presentation principle

Now that everyone knows how to use statelesswidget, how can it be called?

Let’s take a look at the presentation principle.

As mentioned at the beginning, we use the widget as the foundation of the application construction of flutter. In flutter, we call the construction of the widget tree, that is, the widget tree. It’s like the blueprint of an application. We create the blueprint, and then we create the corresponding element element on the screen through the blueprint. It contains the configuration information of the corresponding widget on the blueprint. Therefore, there is also an element tree, that is, the element tree.

Every statelwidget has a statelesselement, and its internal instance is created through the createElement () method

  @override
  StatelessElement createElement() => StatelessElement(this);

At the same time, in statelesselement, the blueprint widget built in the stalesswedget will be obtained through the buid () method, and the elements will be displayed on the screen.

The interaction between widget tree and element tree is as follows

Flying from scratch: statelesswidget

Statelesselement in followertitemview will call build method to get whether it has child parts. If it has, the corresponding child parts will also create their own element and install it to the element tree.

So our program has two corresponding trees, one represents the content element displayed on the screen, and the other represents the blueprint widget, which is composed of many widgets.

What we developers do is build these different widgets into the applications we need.

Finally, let’s take a look at the initial installation portal.

void main() {
  runApp(GithubApp());
}

In our main file, we have a main function, which calls the runApp method and imports GithubApp. Let’s take a look at what GitHub app is?

class GithubApp extends StatefulWidget {
  @override
  _GithubAppState createState() {
    return _GithubAppState();
  }
}
 
class _GithubAppState extends State<GithubApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Github',
      theme: ThemeData.light(),
      initialRoute: welcomeRoute.routeName,
      routes: {
        welcomeRoute.routeName: (BuildContext context) => WelcomePage(),
        loginRoute.routeName: (BuildContext context) => LoginPage(),
        homeRoute.routeName: (BuildContext context) => HomePage(),
        repositoryRoute.routeName: (BuildContext context) => RepositoryPage(),
        followersRoute.routeName: (BuildContext context) =>
            FollowersPage(followersRoute.pageType),
        followingRoute.routeName: (BuildContext context) =>
            FollowersPage(followingRoute.pageType),
        webViewRoute.routeName: (BuildContext context) => WebViewPage(title: '',),
      },
    );
  }
}

It is also a widget. As mentioned at the beginning of the article, flutter is composed of various widgets. Main is the entry of the program, and the widget in the runapp is the starting point of the whole program mounting. It creates a root element with the same width and height as the screen and loads it into the screen.

So in Flutter, we always create the Element and then call the build method to get the subsequent sub Widget, and finally build it into the program we see.

The code in this article is all from flutter_ GitHub, a GitHub client based on flutter, supports both Android and IOS, and supports account password and authentication login. Using dart language for development, the project architecture is MSVM based on Model / state / ViewModel; using navigator for page Jump; using DIO for network framework. The project is being continuously updated. Interested parties can pay attention to it.

Flying from scratch: statelesswidget

Of course, if you want to understand Android native, trust flutter_ The pure Android version of GitHub, awesomegithub, is a good choice.

Next issue notice

Flying from scratch: stateful widget

If you love my article mode or interest in my next article, I suggest you pay attention to my WeChat official account: Android supply station.

Or scan the QR code below to establish effective communication with me and receive my update push faster and more accurately.

Flying from scratch: statelesswidget