![Flutter实战入门](https://wfqqreader-1252317822.image.myqcloud.com/cover/55/32436055/b_32436055.jpg)
上QQ阅读APP看书,第一时间看更新
2.3.2 iOS手机调试运行
可以使用iOS模拟器查看效果,因为模拟器的效果和真机一样。在Android Studio设备选择中选择“open iOS Simulator”创建iOS模拟器,如图2-11所示。
![](https://epubservercos.yuewen.com/E5359F/17517093106688906/epubprivate/OEBPS/Images/t2-11-i.jpg?sign=1738954242-nhnjCGOIBCbVqW8eA6n45PnMRB5tCjCk-0-4d542c3a03bbecaa67d3b1ee68eee1ca)
图2-11 创建iOS模拟器
模拟器创建成功后击“运行”,运行效果如图2-12所示。
![](https://epubservercos.yuewen.com/E5359F/17517093106688906/epubprivate/OEBPS/Images/t2-12-i.jpg?sign=1738954242-EfoQAtyXFyS0wvKF9PqbRwNxFcm3pjtb-0-86c72c34e736f2ca936f84481fb4cf1a)
图2-12 iOS模拟器运行效果
这时我们看到Flutter App已经运行起来了,点击“+”按钮,屏幕中间的数字就会加1,这个效果的实现代码在lib\main.dart中。
void main() => runApp(MyApp());
这是入口函数,运行MyApp。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( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } }
其中,MaterialApp表示使用Material风格(第3章会具体介绍Material风格组件);title为标题;theme为主题,这里可以设置全区主题(第3章会具体介绍theme);home为首页,当前加载的Widget,例子中加载的是MyHomePage Widget。
MyHomePage如下所示:
class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); }
createState方法中创建了_MyHomePageState,如下所示:
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), ), ); } }
其中,_counter属性就是App上展示的数字;incrementCounter方法对counter执行加1操作,点击“+”按钮调用此方法;setState方法中加1会更新到屏幕上;Scaffold是和Material配合使用的控件;AppBar是顶部的区域,如图2-13所示。
![](https://epubservercos.yuewen.com/E5359F/17517093106688906/epubprivate/OEBPS/Images/t2-13-i.jpg?sign=1738954242-4JZDUee1nUKfg0EiC1l8Ldd1kN5y9aL0-0-8f0c55b2c3cb894d13cf065cb6fd2c48)
图2-13 控件界面
body表示AppBar以下区域;Center为容器类控件,子控件居中显示;Column为容器类控件,子控件垂直排列;Text为文本控件;FloatingActionButton为按钮控件,也就是App中“+”按钮。
上面一些控件和方法在后面的相应章节中会具体介绍。