Reputation: 193
return loading ? Loading() : FutureBuilder(
future: SaadConstants.getJsonLanguagePack(),// edit pls
builder: (BuildContext context, AsyncSnapshot snapshot)
{
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
// rest of code
My getJsonLanguagePack():
static Future<String > getJsonLanguagePack() async {
SharedPreferences pref = await SharedPreferences.getInstance();
return json.decode(pref.getString('languagePack')); // languagePack Exists as String already locally containing all the json file content (local json file)
}
My JSON file :
[
{"key":"registerNew", "value":"Nouveau ?" },
{"key":"emailPlaceHolder", "value":"Entrez votre email." },
{"key":"passwordPlaceHolder", "value":"Entrez votre mot de pass." },
{"key":"rememberMe", "value":"rester connecté." },
{"key":"forgotPass", "value":"Pass oublié ?" },
{"key":"loginBtn", "value":"Connexion" },
{"key":"_or_", "value":"_OU_" }]
I tried to return Future> on my getJsonLanguagePack but it raises an error inside FutureBuilder saying that String is not subtype of Map
The problem is when I try to access snapshot.data. I cant use keys that I defined in my JSON file to get the value I want.
As it is conciliated as Array of chars.
Thanks a lot .
Upvotes: 1
Views: 161
Reputation: 15053
You don't have to duplicate json file data into SharePreference
. You can directly use them
import 'dart:convert';
import "package:flutter/material.dart";
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
static Future<Map<String, String>> loadJsonLanguage(String langName) async {
final jsonString = await rootBundle
.loadString('assets/app_languages/' + langName + '.json');
List translationList = jsonDecode(jsonString);
final mappedTranslation = <String, String>{};
translationList.forEach((dynamic item) {
mappedTranslation[item["key"]] = item["value"];
});
return mappedTranslation;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: loadJsonLanguage("ar"),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());
else if (snapshot.hasError)
return Center(child: Text("${snapshot.error}"));
return Center(child: Text(snapshot.data["registerNew"]));
},
),
);
}
}
Upvotes: 1