我制作了一个简单的应用程序,它从JSON文件获取数据标记并将其绘制在GoogleMap上。
我从文件中获取了标记信息,并将其添加到列表DN
中。
但是当我运行我的应用程序时,它只会绘制地图,而不会显示标记,并会收到控制台通知:
.woff application/font-woff
.woff2 application/font-woff2
这是我完整的allMarkers
代码
flutter: Another exception was thrown: A build function returned null.
和我的main.dart
(仅用于测试)
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;
});
}
}
答案 0 :(得分:3)
我不知道您为什么要使用Stack,但您似乎并不需要。
一如既往,在FutureBuilder中添加条件。
FutureBuilder(builder()=>小部件)内部没有返回值。您只是在做一些逻辑,还必须返回一个小部件。
解决方案:
@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,
);
},
),
),
]),
);
}