Flutter IDE模板例子的理解

程序的入口

只需要在runApp中传入Widget就可以了:

void main() => runApp(MyApp());

MyApp

  1. StatelessWidget:无状态Widget
  2. build方法:用于构建一个Widget
  3. MaterialApp:相当于定义一个App的大体结构,将显示的内容(home属性)和全局配置(标题、主题等)分开
  4. MyHomePage:页面内容Widget
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

MyHomePage

看几个关键点:

  1. StatefulWidget:有状态的Widget,可以理解为内容可变
  2. createState方法:因为是有状态的,重写这个方法,创建属于自己的State
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

_MyHomePageState

关键的地方:

  1. 继承State<MyHomePage>:这个泛型的意思就是说这个State的宿主是谁,State是提供给谁用的。可以通过widget拿到MyHomePage实例,比如:widget.title
  2. setState()方法:修改state方法,与React Native的setState相似
  3. Scaffold Widget:Scaffold 是一个Material Design风格的框架。Scaffold已经定义好appBar、body等内容的位置,我们只需要在这里属性中传入Widget。
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
    原文作者:一个不熬夜的孩子
    原文地址: https://www.jianshu.com/p/c9bb96f004be
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞