【发布时间】:2019-10-06 22:55:39
【问题描述】:
我认为我的架构存在缺陷,但我很难了解如何/为什么。我对 Flutter 很陌生,所以请多多包涵。
我有一张地图和一个抽屉。我正在抽屉中加载坐标列表,一旦按下其中一个坐标,我想在地图上做一些事情。
所以我的问题是我不知道在哪里可以调用干净的代码和工作。当然,我可以将所有内容都公开给所有人,但这并不能解决主要问题:我的理解
我的地图和我的抽屉画在同一个地方,所以我已经认为我在作弊,但我认为没关系。老实说,我什至不确定那部分是否真的正确。
绘制地图:
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
var _map = MapView();
var _stationService = StationService();
....
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.map)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike))
],
),
title: Text('Floctta Plus'),
),
drawer: _drawer(),
body: TabBarView(
physics: NeverScrollableScrollPhysics(),
children: [
IncrementView(),
_map,
Icon(Icons.directions_transit),
Icon(Icons.directions_bike)
],
),
),
),
);
}
在我的抽屉代码中:
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, position) {
return ListTile(
title: new Text(snapshot.data[position].titleFR),
leading: new Icon(Icons.pin_drop),
onTap: () {
_map.GoToStation(); <<= Here, calling the MapView class
},
);
},
),
所有 MapView.dart 代码
class MapView extends StatefulWidget {
MapView({Key key}) : super(key: key);
void GoToStation() {
print("I'm reaching this point with success!");
}
@override
_MapViewState createState() => _MapViewState();
}
class _MapViewState extends State<MapView> {
CameraPosition _initialPosition =
CameraPosition(target: LatLng(50.8267018, 4.3532732), zoom: 10.0);
Completer<GoogleMapController> _controller = Completer();
var _markers;
void AddMarkers(List<Station> stations) {
setState(() {
_markers = new List.generate(
stations.length,
(index) => Marker(
markerId: MarkerId(index.toString()),
position: new LatLng(double.parse(stations[index].latitude),
double.parse(stations[index].longitude)),
infoWindow: InfoWindow(
title: stations[index].titleFR,
snippet: stations[index].city,
),
icon: BitmapDescriptor.defaultMarker,
));
});
}
void _onMapCreated(GoogleMapController controller) {
_controller.complete(controller);
}
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: _initialPosition,
markers: _markers,
myLocationEnabled: true,
),
],
);
// );
}
}
我认为有足够的代码。
我的问题是:
我现在在我的 Mapview 课程中,我想打电话给我的 State 课程中的 AddMarkers。但我不能。我不确定我应该如何继续。
我应该直接从抽屉里调用状态类吗?如果是这样,怎么做? 我应该从视图类中调用状态吗?如果是这样,怎么做? 我应该完全做其他事情吗?如果有,是什么?
【问题讨论】:
-
您有几种方法可以做到这一点。我发现最好的方法是使用 BLoC 模式。基本上,你有一个存储库类来跟踪你的标记,然后你的 GoogleMap 将使用来自存储库的流,该流将流式传输标记列表。因此,每次标记更改时,您都会收到更新的标记列表。 google.com/…
-
我读过关于 BLoC 的文章,但我也读过这对于刚开始的人来说太过分了。所以我试图远离它:/但我想如果这是一个解决方案,我最终将不得不进入它:D
-
BLoC 模式只是一种被广泛使用和接受的解决方案的设计模式。如果您想创建更复杂的应用程序,我不建议您远离这些模式,因为这些模式将加快您的编码速度并帮助您创建可维护的代码。
标签: view flutter widget state stateful