我使用谷歌地图在谷歌地图上显示标记。当我输入硬编码的数据时,它会显示标记,但当我将JSON数据传递给标记时,它不会显示。我比较两者没有区别,两者都是一个标记列表。有人能告诉我我做错了什么吗?这是我的代码
import 'dart:async';
import 'dart:convert';
import 'package:CityKey/providers/businesses.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
class MapsScreen extends StatefulWidget {
static const routeName = '/maps-screen';
@override
_MapsScreenState createState() => _MapsScreenState();
}
class _MapsScreenState extends State<MapsScreen> {
Completer<GoogleMapController> _controller = Completer();
Set<Marker> markers = {};
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
final businesses = Provider.of<Businesses>(context, listen: false);
final jsonBusiness = json.encode(businesses.business.toList());
List<Marker> list = [
Marker(
markerId: MarkerId('Marker1'),
position: LatLng(32.195476, 74.2023563),
infoWindow: InfoWindow(title: 'Business 1'),
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),
),
Marker(
markerId: MarkerId('Marker2'),
position: LatLng(32.162969, 74.193625),
infoWindow: InfoWindow(title: 'Business 2'),
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
),
Marker(
markerId: MarkerId('Marker3'),
position: LatLng(32.139505, 74.209312),
infoWindow: InfoWindow(title: 'Business 2'),
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),
),
];
print('List of markers $list');
// setState(() {
// markers.addAll(list);
// });
// print('list of markers $markers');
final List jsonList = json.decode(jsonBusiness);
final List listofLatLong = jsonList
.map(
(e) => Map.fromEntries([
MapEntry(
'business_address_longitude',
e['business_address_longitude'],
),
MapEntry(
'business_address_latitude',
e['business_address_latitude'],
),
MapEntry(
'business_title',
e['business_title'],
),
MapEntry(
'business_id',
e['business_id'],
),
]),
)
.toList();
final title = listofLatLong
.map((e) => Marker(
markerId: MarkerId('Marker${e['business_id']}'),
position: LatLng(
double.parse(e['business_address_latitude']),
double.parse(e['business_address_latitude']),
),
infoWindow: InfoWindow(
title: e['business_title'],
),
icon: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueBlue),
))
.toList();
print('List of markers my $title');
setState(() {
markers.addAll(title);
});
// print(markers);
// print('This is the business ');
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Maps'),
),
body: GoogleMap(
markers: Set<Marker>.of(markers),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
initialCameraPosition: CameraPosition(
target: LatLng(32.1749132, 74.1779387),
zoom: 11.0,
),
),
);
}
}
发生这种情况的原因是我正在使用提供程序包来获取我存储在var中的值,当它在构建上下文中输入时,所提供的值正在更改。我所做的一切都存储在final中,然后将参数传递到map,它解决了我的问题。