【发布时间】:2022-01-22 20:16:01
【问题描述】:
我是 Flutter 和一般移动应用程序开发的新手,如果我犯了任何明显的错误,非常抱歉。我有一个 Flutter_map 应用程序,并使用 API 生成并使用折线绘制路线。我有一个按钮,当按下它时,它可以设置在路由期间要避开的区域。在按下按钮后,我添加了一个代码块来动态添加标记(第二个 sn-p),但是当我添加它们时,之前绘制的路线消失了。此外,用于包含数据的列表始终为空。我怀疑 setState 对此负责。这是我的代码的一部分,我排除了一些部分,所以它可以阅读。
void main() => runApp(MyApp());
List<Marker> markers = [];
class NetworkHelper {
NetworkHelper({
required this.startLng,
required this.startLat,
required this.endLng,
required this.endLat
});
Future getstuff() async {
http.Response response;
API = response; //pseudocode but works properly
}
}
class MyApp extends StatelessWidget {
//root of app
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Map',
home: MyMap(),
debugShowCheckedModeBanner: false,
);
}
}
class MyMap extends StatefulWidget {
@override
_MyMap createState() => _MyMap();
}
class _MyMap extends State<MyMap> with SingleTickerProviderStateMixin{
static const String route = 'map';
@override
Widget build(BuildContext context) {
final List<Polyline> avoids_set = [];
final List<LatLng> polyPoints = [];
var data;
double endLat = 24.8547;
double endLng = 54.7518;
void getJsonData() async {
NetworkHelper network = NetworkHelper(
startLat: position.latitude,
startLng: position.longitude,
endLat: endLat,
endLng: endLng,
);
try{
data = await network.getstuff();
//create polylines --correct
}catch(e){}
}
//---
//update all data here
//---
我提供了一个大代码块,因为我认为我必须在代码中添加很多元素才能使其工作。我还有一个生成路由的按钮,如代码所示
return Scaffold(
appBar: AppBar(title: Text('Map'),backgroundColor: Colors.red),
floatingActionButton: Stack(
fit: StackFit.expand,
children: [
// Route button
Positioned(
bottom: 20,
right: 20,
child: FloatingActionButton(
onPressed: (){
getJsonData();
},
child: const Icon(Icons.navigation,size: 35),
backgroundColor: Colors.green,
),
),
// button
Positioned(
bottom: 90,
right: 20,
child: FloatingActionButton(
onPressed: button,
child: const Icon(Icons.,size: 35),
backgroundColor: Colors.red,
),
),
]
),
body:
FlutterMap(
options: MapOptions(
// press for latlng points
onLongPress: (position,latlng){
LatLng temp = latlng;
Marker marker = Marker(point: latlng,
builder: (ctx) =>
Container(
child: Icon(
Icons.circle_sharp,
size: 30,
color: Colors.red,
),
),
);
//------------------IMPORTANT--------------------
markers.add(marker);
setState(() {
marker = marker;
});
}
},
layers: [
TileLayerOptions(
----
MarkerLayerOptions(
markers: markers,
),
],
),
);
}
}
基本上,我需要动态添加标记,但没有 setState 函数,或者调整应用程序以使 setState 与应用程序的其他功能一起使用。 任何帮助表示赞赏!
【问题讨论】: