Flutter学习记录(二、Flutter项目学习Widget)
生活随笔
收集整理的這篇文章主要介紹了
Flutter学习记录(二、Flutter项目学习Widget)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在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{@overrideWidget build(BuildContext context) {return new Scaffold(appBar: new AppBar(leading:new Text("我是誰?"),title: new Text('齊天大圣崔雪峰'),actions: <Widget>[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{@overrideState<StatefulWidget> createState() {return new StateA();} }class StateA extends State{int count=0;change(){setState(() {count++;});}@overrideWidget 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: <Widget>[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{@overrideState<StatefulWidget> createState() {return new StateA();} } class StateA extends State{int count=0;void change(int count){setState(() {this.count=count+1;});}@overrideWidget 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);}@overrideWidget 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: <Widget>[new RaisedButton(onPressed: change,child: new Text('add'),),new Text('Count:'+count.toString()),],));}} 父組件向子組件傳遞count和函數消息,子組件通過父組件傳遞進來的函數向父組件發送count消息。總結
以上是生活随笔為你收集整理的Flutter学习记录(二、Flutter项目学习Widget)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: greys使用
- 下一篇: Flutter学习记录(三、Flutte