我制作了一个简单的应用程序,从JSON文件中获取数据标记,然后在谷歌地图上绘制它们。
我已经从文件中获取了标记信息并将其添加到列表中。
但当我运行我的应用程序时,它只绘制地图,而不是显示标记,并得到一个控制台通知:allMarkers
这是我的完整代码
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future _future;
Future<String> loadString() async =>
await rootBundle.loadString('assets/data.json');
List<Marker> allMarkers = [];
GoogleMapController _controller;
@override
void initState() {
// TODO: implement initState
super.initState();
_future = loadString();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(children: [
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(children: <Widget>[
FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot snapshot) {
List<dynamic> parsedJson = jsonDecode(snapshot.data);
allMarkers = parsedJson.map((element) {
return Marker(
markerId: MarkerId(element['id']),
position: LatLng(element['x'], element['y']));
}).toList();
},
),
GoogleMap(
initialCameraPosition:
CameraPosition(target: LatLng(40.7128, -74.0060), zoom: 1.0),
markers: Set.from(allMarkers),
onMapCreated: mapCreated,
),
]),
),
]),
);
}
void mapCreated(controller) {
setState(() {
_controller = controller;
});
}
}
和my
flutter: Another exception was thrown: A build function returned null.
(仅用于测试)[{
"id": "8D5D-4CD323560F59",
"x": 40.7128,
"y": -74.0060
},{
"id": "E3E0D2C5-CB82",
"x": 41.7128,
"y": -75.0060
}]
最佳答案
我不知道你为什么要用Stack,但你似乎不需要这么远。
在FutureBuilder中添加条件应该和下面的示例一样。FutureBuilder(builder: () => Widget)
中没有返回值。在您的例子中,您只是在做一些逻辑,您还必须返回一个小部件。
解决方案:
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(children: [
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
List<dynamic> parsedJson = jsonDecode(snapshot.data);
allMarkers = parsedJson.map((element) {
return Marker(
markerId: MarkerId(element['id']),
position: LatLng(element['x'], element['y']));
}).toList();
return GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(40.7128, -74.0060), zoom: 1.0),
markers: Set.from(allMarkers),
onMapCreated: mapCreated,
);
},
),
),
]),
);
}
关于google-maps - 从JSON文件中获取Marker并在Google Map上显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56208104/