I am able to fetch data from shared preferences. I want to reload the data on the page after reopening the app fetching data from shared preferences. Right now, im trying to load data from shared preferences to a list which is called in the initState().
Note:- when i navigate to other page and come page to page on which data needs to be updated. The data is updated successfully. But i want to do this everytime app is opened again
class WeatherApp extends StatefulWidget {
const WeatherApp({Key? key}) : super(key: key);
static const String idScreen = "weather";
@override
_WeatherAppState createState() => _WeatherAppState();
}
class _WeatherAppState extends State<WeatherApp> {
final preferenceService = PreferencesService();
@override
void initState() {
super.initState();
WidgetsBinding.instance!.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance!.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print('state = $state');
if (state == AppLifecycleState.resumed){
setState(() {
preferenceService.getData();
});
}
}
class PreferencesService{
void saveData(List<dynamic> data) async{
final preferences = await SharedPreferences.getInstance();
String encodedData = jsonEncode(data);
await preferences.setString("weather_data", encodedData);
}
void getData() async{
final preferences = await SharedPreferences.getInstance();
var jsonData = preferences.getString("weather_data");
if (jsonData == null){
locationList = [];
}
else{
locationList.clear();
var dataList = json.decode(jsonData);
for (var e in dataList) {
locationList.add(
WeatherModel(
weatherId: e["weatherId"],
cityId: e["cityId"],
city: e["city"],
dateTime: e["dateTime"],
temperature: e["temperature"],
weatherType: e["weatherType"],
iconUrl: e["iconUrl"],
wind: e["wind"],
rain: e["rain"],
humidity: e["humidity"],
)
);
print("fetching Data");
print(locationList);
}
}
}
}
Im trying to update text for which i have made another stateful widget(Text is not updating even after saving data to a global list and fetching data on resumed)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(locationList.length != 0 ? locationList[widget.index].temperature : "--\u2103"),
Row(
children: [
SvgPicture.asset(locationList.length != 0 ? locationList[widget.index].iconUrl : "assets/rain.svg", width: 30,height: 30,color: Colors.white,),
Text(locationList.length != 0 ? locationList[widget.index].weatherType : "Rainy",style: GoogleFonts.openSans(fontSize: 20,fontWeight: FontWeight.bold,color: Colors.white)),
],
),
],
),
],
),