flutter 組件通信學習~
父子組件正向傳值
class Parent extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return ParentState();
}
}
class ParentState extends State<Parent> {
String data = "無";
String dataTwo = "傳遞給組件2的值";
void onChanged(val){
setState(() {
data = val;
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Container(
width: 400,
margin: const EdgeInsets.all(10),
padding: const EdgeInsets.only(top: 30, bottom: 50),
decoration: BoxDecoration(color: Colors.blue[100]),
child: new Column(
children: <Widget>[
new childOne(),
new childTwo(dataTwo: dataTwo,callBack: (value)=>onChanged(value)),
new Container(
padding: new EdgeInsets.only(bottom: 15),
child: new Text('父組件'),
),
new Text('子組件2贞岭,傳過來的值' + '$data'),
],
),
),
],
),
);
}
}
定義父組件變量 dataTwo脑沿,在子組件childTwo的構造方法中把值穿進去昆禽。
在childTwo中重新定義構造方法。其中dataTwo就是從父組件傳進來的值。
class childTwo extends StatefulWidget {
childTwo({Key key, this.dataTwo, this.callBack}) : super(key: key);
final callBack;
String dataTwo;
對于dataTwo的值我們可以在 initState中通過widget.dataTwo拿到蹈矮。
@override
void initState() {
// TODO: implement initState
data = widget.dataTwo;
super.initState();
}
父子組件間逆向傳值
其實父子組件傳值有點像vue的傳值,搞過vue的應該挺好理解這個鸣驱。
自定義構造方法中
void onChanged(val){
setState(() {
data = val;
});
}
new childTwo(dataTwo: dataTwo,callBack: (value)=>onChanged(value))
在父組件提前定義好泛鸟,接收到子組件調用的方法,onchanged踊东。
在子組件中
自定義構造方法把callBack方法傳進來
childTwo({Key key, this.dataTwo, this.callBack}) : super(key: key);
final callBack;
String dataTwo;
可以調用下面的方法進行傳值北滥。
widget.callBack('$inputText');
組件和組件之間的傳值
在這里運用event_bus來實現(xiàn)傳值。
import 'package:event_bus/event_bus.dart';
event_bus用法闸翅。
新建消息監(jiān)測類
import 'package:event_bus/event_bus.dart';
EventBus eventBus = new EventBus();
class TransEvent{
String text;
TransEvent(this.text);
}
監(jiān)測類變化
eventBus.on<TransEvent>().listen((TransEvent data) => show(data.text));
void show(String val) {
setState(() {
data = val;
});
}
觸發(fā)消息變化
eventBus.fire(new TransEvent('$inputText'));
這樣我們就可以根據(jù)這些來實現(xiàn)組件之間的傳值再芋。
https://github.com/Butteryflyyer/FlutterStudyDemo這是我學習flutter的代碼地址,平時寫的demo都會放到這里面坚冀。