HelloWorld整体代码
先快速写一个最简单的结构体,这个界面只包含两部分,头部订单的蓝色bar条和屏幕中间区域的内容。(请看下面代码)
这段代码写在根目录\lib\main.dart文件中,这就是Flutter主文件。
[AppleScript] 纯文本查看 复制代码
?
1 |
[mw_shl_code = javascript , true ]import 'package : flutter / material.dart'; / / 主函数(入口函数),下面我会简单说说Dart的函数void main ( ) = > runApp ( MyApp ( ) ) ; / / 声明MyApp类 class MyApp extends StatelessWidget { / / 重写build方法 @override Widget build ( BuildContext context ) { / / 返回一个Material风格的组件 return MaterialApp ( title : 'Welcome to Flutteraa' , home : Scaffold ( / / 创建一个Bar,并添加文本 appBar : AppBar ( title : Text ( 'Welcome to Flutter' ) , ) , / / 在主体的中间区域,添加一个hello world 的文本 body : Center ( child : Text ( 'Hello World' ) , ) , ) , ) ; } } |
[/mw_shl_code]
写完后打开终端,运行flutter run,等待一小会,就会看到虚拟机中显示了Hello World的内容。
也许你对上面的语法还不够了解,但你不必惊慌,我们会一点点进行说明,那先来看一下Dart中的函数。
Dart语法Function函数
Dart是面向对象的语言,即使是函数也是对象,并且属于Function类型的对象。这意味着函数可以分配给变量或作为参数传递给其他函数。当然你也可以像JavaScript一样,调用一个函数。
比如我们写Hello World中的第2行,就是一个函数。
[AppleScript] 纯文本查看 复制代码
?
1 |
void main ( ) = > runApp ( MyApp ( ) ) ; |
因为这个函数体里只有一行代码,所以可以直接使用=>来省略{},只有函数体里只有一行时,才可以使用,否则请使用大括号。
(ps:学习Dart语法时你要记住一条,Dart里一切皆对象,包括数字和函数.......,没对象的程序员小哥哥可要抓紧学习了,程序中自有颜如玉的时代到了)
[size=0.85em]#StatefulWidget和StatelessWidget
- StatefulWidget : 具有可变状态的窗口部件,也就是你在使用应用的时候就可以随时变化,比如我们常见的进度条,随着进度不断变化。
- StatelessWidget:不可变状态窗口部件,也就是你在使用时不可以改变,比如固定的文字(写上后就在那里了,死也不会变了)。
这个HelloWorld代码就继承了不可变窗口部件StatelessWidget。
VSCode中如何热加载
用VSCode编写Flutter不好的一点就是要手动加载更新应用,个人感觉这至少会降低10%的工作效率。
当我们运行flutter run以后,会有一段红色文字的提示,说明了我们可以作的事情。
[AppleScript] 纯文本查看 复制代码
?
1 |
To hot reload changes while running , press "r" . To hot restart ( and rebuild state ) , press "R" .An Observatory debugger and profiler on Android SDK built for x 86 isavailable at : [ url ]http : / / 127.0 . 0.1 : 64590 / You[ / url ] can dump the widget hierarchy of the app ( debugDumpApp ) by pressing "w" .To dump the rendering tree of the app ( debugDumpRenderTree ) , press "t" .For layers ( debugDumpLayerTree ) , use "L" ; for accessibility ( debugDumpSemantics ) , use "S" ( for traversal order ) or "U" ( for inverse hit test order ) .To toggle the widget inspector ( WidgetsApp.showWidgetInspectorOverride ) , press "i" .To toggle the display of construction lines ( debugPaintSizeEnabled ) , press "p" .To simulate different operating systems , ( defaultTargetPlatform ) , press "o" .To display the performance overlay ( WidgetsApp.showPerformanceOverlay ) , press "P" .To save a screenshot to flutter.png , press "s" .To repeat this help message , press "h" . To detach , press "d" ; to quit , press "q" . |
我们来看几个重点的:
- r 键:点击后热加载,也就算是重新加载吧。
- p 键:显示网格,这个可以很好的掌握布局情况,工作中很有用。
- o 键:切换android和ios的预览模式。
- q 键:退出调试预览模式。
常用的一般就这些,剩下的命令以后碰到我们再进行讲解。
如果你觉的这太麻烦了,我们可以开启Debug模式,这时就可以实现真正的热加载了(我们保存,效果立即就会改变),但有时报错也挺烦人的。