flutter 父組件調用自組件方法

1、在自組件中
重要的是 這句代碼 GlobalKey<_ChildState> globalKey = GlobalKey();

import 'package:flutter/material.dart';

GlobalKey<_ChildState> globalKey = GlobalKey();

class Child extends StatefulWidget {
  Child({
    Key key,
  }) : super(key: key);
  @override
  _ChildState createState() => _ChildState();
}
class _ChildState extends State<Child> {
	
	//子組件方法
	childMethod(){}
	....
}

2、父組件中

import 'package:flutter/material.dart';

class Parent extends StatefulWidget {
  Parent({}) : super(key: key);
  @override
  _ParentState createState() => _ParentState();
}
class _ParentState extends State<Parent> {
	parentMethod(){
		//父組件中調用
		globalKey.currentState.childMethod(_contractOrder)
	}
 	@override
  	Widget build(BuildContext context) {
    	return Child(key: globalKey)
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章