Load and read data from Json file

2020-05-08 08:44发布

问题:

I create simple app get data of marker from json file and draw them. The code below is get data from data.json and add to the list of marker.

I got problem. I can't get data from json file and add it to my marker list. How can I do that?

My main.dart code

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();
  }
}

My 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,
  },

回答1:

Try this.

1) You have to add the data.json file in assests.

2) Then add in to pubspec.yaml file.

assets: - assets/data.json

3) Then add this below code.

String jsonData = await DefaultAssetBundle.of(context).loadString("assets/data.json"); final jsonResult = json.decode(jsonData);



回答2:

I think this is what you are looking for.

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});
}



标签: dart flutter