![](/img/trans.png)
[英]how to add a JSON file data into Cloud Firestore + Flutter
[英]Flutter: How to download Json file to local then access it
目前,我正在通过DefaultAssetBundle
访问特定的 JSON 文件country.json
,如下所示:
Future<List<Country>> getCountryFromJson(BuildContext context) async {
String jsonString =
await DefaultAssetBundle.of(context).loadString('assets/country.json');
List<dynamic> raw = jsonDecode(jsonString);
return raw.map((e) => Country.fromJson(e)).toList();
}
但是我想通过将其上传到FirebaseStorage来更新新的 json 文件(同名),然后每次打开应用程序时,它都会通过get http
下载新文件并稍后访问(当新文件没有时,应用程序仍会访问旧文件'未完成下载)
所以我想问如何做到以下几点:
- 选项 1:从 Http 链接下载新文件country.json
并覆盖资产中的旧文件
- 选项 2:如果无法干扰资产,则尽可能将其下载到本地存储中,并优先访问资产中的新文件而不是旧文件
这是主文件:
import 'dart:convert';
import 'dart:core';
import 'package:ask/country.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<List<Country>> getCountryFromJson(BuildContext context) async {
String jsonString =
await DefaultAssetBundle.of(context).loadString('assets/country.json');
List<dynamic> raw = jsonDecode(jsonString);
return raw.map((e) => Country.fromJson(e)).toList();
}
Widget build(BuildContext context) {
return new MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Country')),
body: Container(
child: FutureBuilder(
future: getCountryFromJson(context),
builder: (context, data) {
if (data.hasData) {
List<Country> countries = data.data;
return ListView.builder(
itemCount: countries.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: Column(children: <Widget>[
Text(
countries[index].country,
)
]));
});
} else {
return Center(child: CircularProgressIndicator());
}
}))));
}
}
您可以按照 Firebase 云存储上的指南下载 Flutter 中的文件。 文档中还讨论了如何将文件上传到 Cloud Storage 的步骤。 然后更新本地 json 文件,您可以将 json 和 map 读取到模型/对象或列表。
File file = File('${PATH}/country.json');
String jsonText = await file.readAsString();
final parsed = jsonText(responseBody).cast<Map<String, dynamic>>(););
List<Country> listCountry = parsed.map<Photo>((json) => Country.fromJson(json)).toList();
然后,您可以使用List.insert(index, Object)
或List.add(Object)
在列表中插入另一个国家。 如果您需要帮助将 json 序列化为 model 以在列表中添加新条目,您可以查看本指南。
Country
的 model 可能看起来像这样。
class Country {
final int countryId;
final int countryName;
const Country({
required this.countryId,
required this.countryName,
});
factory Country.fromJson(Map<String, dynamic> json) {
return Photo(
countryId: json['country_id'] as String,
countryName: json['country_name'] as String,
);
}
}
但是,由于您已经在使用 Firebase 产品,您可能需要考虑使用Cloud Firestore ,因为您描述的用例似乎与 Firestore 的功能相匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.