欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Flutter学习记录(二、Flutter项目学习Widget)

发布时间:2025/3/19 编程问答 30 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。