flutter hello world源码解析

顾嘉德
2023-12-01

flutter hello world源码解析

在android studio 配置flutter工程后,主工程代码如下。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
    //应用名称
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        // 可以通过该属性设置toolbar的颜色值,这里介绍了flutter的hot reload的热部署,可以不用重启应用来更新代码**
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        //自适应像素密度。
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      //路由首页
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0; //定义计数器

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        //标题栏
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

1 import ‘package:flutter/material.dart’;表示引入可以使用的组件库,Flutter提供了丰富的Material widget,有点类似于android 的material design组件库和view组件库的集合。

2 runApp(MyApp()); 将MyApp这个widget渲染到屏幕上,如果再调用runApp(Widget widget)的时候会覆盖替换原来渲染在屏幕上的组件。这里,我们可以理解widget为android 的view。

3 MyApp extends StatelessWidget,在flutter看来,一切都是widget,包括alignment、padding、layout,widget包含了要渲染视图的所有信息,包括位置,间距、背景、渲染的样子等等。

4 Widget build(BuildContext context),widget在创建时会调用该方法来构建widget树结构,类似于android的view树一样。

5 MaterialApp是一个app的框架,类似于android application,通过这个类的构造函数可以设置应用的名称、主题、首页、路由等信息。

6 MyHomePage extends StatefulWidget,MyHomePage 是一个有状态的widget,StatefulWidget和StatelessWidget 的区别在于StatefulWidget内部维护了一个State的对象,通过这个对象的setState方法可以通知flutter去重新渲染widget。StatefulWidget通过createState创建了state,并将StatefulWidget的构建树工作交给了state,这样做的目的我认为是:在构建widget树的过程中,各个widget可能会引用到state设置的状态属性,这样各个widget作为state的内部类可以自由访问这些属性。

7 setState,通知flutter框架有状态变更,去重新渲染widget,同时回调state的build(BuildContext context)方法。

8 Scaffold是一个基于material design的基础布局框架。提供了设置导航栏、appBar标题栏、以及body等方法,有点类似于android的activity,而body有点类似于content。

9 Center是一个布局,这个布局只有一个widget,并且把这个widget放在了中心位置。

10 Column也是一个布局,这个布局有点类似于android 的LinearLayout设置oritation = vertical。

11 mainAxisAlignment表示主轴的对齐方式,这里主轴的方向的vertical,就是说Column的child在竖直方向的对其方式。

12 children: 表示Column里面的children有哪些,我们注意到flutter设置参数都是类似于 children: 这种方式,这个是dart的可选命名参数的语法,可以通过“children:a”这种方式来通知函数传参的是哪一个参数。

13 Text是flutter显示文字的一个widget,有点类似于android textview。

14 floatingActionButton是flutter可以点击的一个widget,有点类似于android的悬浮菜单按钮FloatingActionButton,该组件通过onPressed来回调_incrementCounter方法来设置计数器增加的同事刷新widget。

以上就是对flutter初次使用的理解。

 类似资料: