我正在使用flutter应用程序。我获取演示json文件
dummy JSON file
使用此URL获取JSON值。但是当我尝试添加在assets文件夹中创建的JSON文件和在代码中添加的文件目录路径时。但它不起作用
pubspec.yaml
我像这样添加的文件
assets:
- assets/test.json
.
import 'package:flutter/services.dart' show rootBundle;
Future<Map> _loadAStudentAsset() async {
return await rootBundle.loadString('assets/test.json');
}
我做错了什么。有人能推荐我吗?如何使用同一项目文件夹中的json文件。请随时告诉我代码中是否有错误。
这是我的工作代码。
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
Map data;
List features;
void main() async {
data = await getQuakes();
features = data['features'];
runApp(new MaterialApp(
title: 'Quakes',
home: new Quakes(),
));
}
class Quakes extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Quakes'),
centerTitle: true,
backgroundColor: Colors.red,
),
body: new Center(
child: new ListView.builder(
itemCount: features.length,
padding: const EdgeInsets.all(15.0),
itemBuilder: (BuildContext context, int position) {
if (position.isOdd) return new Divider();
final index = position ~/
2;
var format = new DateFormat.yMMMMd("en_US").add_jm();
var date = format.format(new DateTime.fromMicrosecondsSinceEpoch(
features[index]['properties']['time'] * 1000,
isUtc: true));
return new ListTile(
title: new Text(
" $date",
style: new TextStyle(
fontSize: 15.5,
color: Colors.orange,
fontWeight: FontWeight.w500),
),
subtitle: new Text(
"${_features[index]['properties']['place']}",
style: new TextStyle(
fontSize: 14.5,
fontWeight: FontWeight.normal,
color: Colors.grey,
fontStyle: FontStyle.italic),
),
leading: new CircleAvatar(
backgroundColor: Colors.green,
child: new Text(
"${_features[index]['properties']['mag']}",
style: new TextStyle(
fontSize: 16.5,
fontWeight: FontWeight.bold,
color: Colors.white,
fontStyle: FontStyle.normal),
),
),
onTap: () {
showAlertMessage(
context, "${_features[index]['properties']['title']}");
},
);
}),
),
);
}
void _showAlertMessage(BuildContext context, String message) {
var alert = new AlertDialog(
title: new Text('Quakes'),
content: new Text(message),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: new Text('OK'))
],
);
showDialog(context: context, builder: (context) => alert);
}
}
Future<Map> getQuakes() async {
String apiUrl =
'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';
http.Response response = await http.get(apiUrl);
return json.decode(response.body);
}