在flutter当中,所有页面元素都是一个Widget,一个文本显示是widget,一个包含文本显示的容器也是widget,下面是三个demo:
1、一个简单的显示titlebar的app
import 'package:flutter/material.dart';
void main() => runApp(new MaterialApp(
title: 'Flutter Tutorial',
home: new Home(),
));
class Home extends StatelessWidget{
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
leading:new Text("我是谁?"),
title: new Text('齐天大圣崔雪峰'),
actions: [
new IconButton(
icon: new Icon(Icons.search),
tooltip: 'Search',
onPressed: null,
),
]
),
//body占屏幕的大部分
body: new Center(
child: new Text('Hello, world!'),
),
);
}
}
首先,meterial.dart作为引入的资源库;main方法是运行app的入口程序,“=>”写法等同于{};Home是一个无状态的Widget,复写build用于创建页面元素,此例子包含一个画布Scaffold,Scaffold中有一个AppBar,和一个Center,AppBar中又有两个Text和一个IconButton,这些都是widget。
2、一个有状态的Widget
import 'package:flutter/material.dart';
void main() => runApp(new MaterialApp(
title: 'Flutter Tutorial',
home: new Home(),
));
class Home extends StatefulWidget{
@override
State createState() {
return new StateA();
}
}
class StateA extends State{
int count=0;
change(){
setState(() {
count++;
});
}
@override
Widget build(BuildContext context) {
return new Container(
height: 56.0, // 单位是逻辑上的像素(并非真实的像素,类似于浏览器中的像素)
padding: const EdgeInsets.symmetric(horizontal: 8.0),
decoration: new BoxDecoration(color: Colors.blue[500]),
child:new Row(
children: [
new RaisedButton(
onPressed: change,
child: new Text('add'),
),
new Text('Count: $count'),
],
)
);
}
}
此例中home设定为一个有状态的widget-StatefulWidget,Home不做任何事情仅用于承载State组件createState返回一个State子类-StateA,StateA里面可以有一个方法中实现setState方法用于动态的改变count的值。
3、父组件和子组件传递消息
在flutter中,父组件向子组建传递消息直接实例化赋值即可,子组件向父组件传递消息比较麻烦需要使用事件冒泡
import 'package:flutter/material.dart'; void main() => runApp(new MaterialApp( title: 'Flutter Tutorial', home: new Home(), )); class Home extends StatefulWidget{ @override StatecreateState() { return new StateA(); } } class StateA extends State{ int count=0; void change(int count){ setState(() { this.count=count+1; }); } @override Widget build(BuildContext context) { return new StateB(count:count,onChanged: change,); } } class StateB extends StatelessWidget{ StateB({Key key, this.count: 0, @required this.onChanged}): super(key: key); final int count; final onChanged; void change(){ onChanged(count); } @override Widget build(BuildContext context) { return new Container( height: 56.0, // 单位是逻辑上的像素(并非真实的像素,类似于浏览器中的像素) padding: const EdgeInsets.symmetric(horizontal: 8.0), decoration: new BoxDecoration(color: Colors.blue[500]), child:new Row( children: [ new RaisedButton( onPressed: change, child: new Text('add'), ), new Text('Count:'+count.toString()), ], ) ); } } 父组件向子组件传递count和函数消息,子组件通过父组件传递进来的函数向父组件发送count消息。