[英]How to access other classes method in flutter (dart)?
我在腳手架中使用了顫振圖,並且在腳手架小部件類中有一個名為“showMyBottomSheet”的方法。 當點擊地圖並打開底部工作表時用於執行此方法的地圖。
但是現在我已將這兩個文件分開在單獨的文件中,我無法從地圖類訪問腳手架有狀態小部件中的“showMyBottomSheet”方法。
我該怎么做? 我不應該把它們分開嗎?
我的主頁 - home.dart
class MyHomePage extends StatefulWidget {
static const String route = '/';
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static const String route = '/';
// Bottom sheet
final _scaffoldKey = new GlobalKey<ScaffoldState>();
dynamic showMyBottomSheet(LatLng latlang) {
_scaffoldKey.currentState.showBottomSheet((context) {
return new CustomBottomSheet();
});
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
drawer: buildDrawer(context, route),
body: new Column(
children: [
new CustomMap(),
],
),
);
}
}
地圖小部件 - flutterMap.dart
class Cuenter code herestomMap extends StatefulWidget {
@override
_CustomMapState createState() => new _CustomMapState();
}
class _CustomMapState extends State<CustomMap> {
var markers = <Marker>[];
@override
Widget build(BuildContext context) {
return new Flexible(
child: new FlutterMap(
options: new MapOptions(
center: new LatLng(51.25, 30.5),
zoom: 15.0,
onTap: // I want to call showMyBottomSheet method (from home page) here
),
layers: [
new TileLayerOptions(
urlTemplate:
"https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c']),
],
),
);
}
}
首先,請注意任何以下划線開頭的方法在 Dart 中都將被視為私有方法。 看這里。
在這種情況下,您應該將該方法傳遞給子小部件並稍后調用它。 檢查這個例子:
class MyHomePage extends StatefulWidget {
static const String route = '/';
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static const String route = '/';
// Bottom sheet
final _scaffoldKey = new GlobalKey<ScaffoldState>();
dynamic showMyBottomSheet(LatLng latlang) {
_scaffoldKey.currentState.showBottomSheet((context) {
return new CustomBottomSheet();
});
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
drawer: buildDrawer(context, route),
body: new Column(
children: [
new CustomMap(onMapTap: showMyBottomSheet),
],
),
);
}
}
在 flutterMap.dart 中:
class CustomMap extends StatefulWidget {
Function onMapTap;
CustomMap({this.onMapTap});
@override
_CustomMapState createState() => new _CustomMapState();
}
class _CustomMapState extends State<CustomMap> {
var markers = <Marker>[];
@override
Widget build(BuildContext context) {
return new Flexible(
child: new FlutterMap(
options: new MapOptions(
center: new LatLng(51.25, 30.5),
zoom: 15.0,
onTap: (){
widget.onMapTap(LatLng(34.12312,56.1323));
}
),
layers: [
new TileLayerOptions(
urlTemplate:
"https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c']),
],
),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.