我创建简单的应用程序,从json文件中获取标记的数据并绘制它们。下面的代码是从data.json
获取数据并添加到标记列表中。
我有麻烦了。我无法从json文件中获取数据并将其添加到我的标记列表中。我该怎么做呢?
我的main.dart
代码
class MapSample extends StatefulWidget {
@override
State<MapSample> createState() => MapSampleState();
}
class MapSampleState extends State<MapSample> {
@override
void initState() {
var location = Location();
FutureBuilder(
future:
DefaultAssetBundle.of(context).loadString('assets/data.json'),
builder: (context, snapshot) {
// Decode the JSON
var new_data = json.decode(snapshot.data.toString());
for (var i = 0; i < new_data.length; i++) {
location = Location(
id: new_data[i]['id'],
lat: new_data[i]['x'],
long: new_data[i]['y'],
);
locations.add(location);
//print(location.lat);
}
});
super.initState();
}
}
我的data.json
[{
"rownum": 1,
"id": "E3E0D2C5-CB82-4AF3-8D5D-4CD323560F59",
"x": 10.99803453,
"y": 106.65676933,
}, {
"rownum": 2,
"id": "5FFB6736-7D1F-4B40-A397-32EB3128BC30",
"x": 10.99793271,
"y": 106.65666751,
},
发布于 2019-05-15 11:10:04
尝尝这个。
中
然后将
assets:
- assets/data.json
String jsonData = await DefaultAssetBundle.of(context).loadString("assets/data.json");
final jsonResult = json.decode(jsonData);
发布于 2019-05-15 16:10:48
我想这就是你要找的。
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() {
runApp(Test());
}
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
Future _future;
List<Location> locations;
Future<String> loadJson() async =>
await rootBundle.loadString('assets/data.json');
@override
void initState() {
_future = loadJson();
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder(
future: _future,
builder: (context, snapshot) {
if (snapshot.hasData) {
for (var v in snapshot.data) {
locations.add(Location(
id: v['id'],
lat: v['x'],
long: v['y'],
));
}
return Text(snapshot.data);
} else {
return CircularProgressIndicator();
}
}),
),
);
}
}
class Location {
final String id;
final double lat;
final double long;
Location({this.id, this.lat, this.long});
}
https://stackoverflow.com/questions/56141871
复制相似问题