i want to receive data from a map i received from sharedpreference.
the Data looks like this:
{2022-04-08 15:49:41.864929: 1234567, 2022-04-08 15:49:55.392684: 1234567, 2022-04-08 15:50:17.168655: 1234567, 2022-04-08 15:50:39.263044: 1234567}
The date is they key, and the numbers the value. Now i need to display all 4 keys and the values in 4 listtiles. How is this possible? I am really new in flutter.
_saveData() async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(DateTime.now().toString(), '1234567');
}
_clearData() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.clear();
print('Daten gelöscht');
}
_loadData() async {
final prefs = await SharedPreferences.getInstance();
final keys = prefs.getKeys();
final prefsMap = Map<String, dynamic>();
for(String key in keys) {
prefsMap[key] = prefs.get(key);
}
print(prefsMap);
}```
I included a rough example here.
You can check out the demo at https://dartpad.dev/087d5cfc1044c8ce742a0c5c7147940f
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatelessWidget(),
),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
// An example of using Future to return Map<String, dynamic>
Future<Map<String, dynamic>> _loadData() async {
Map<String, dynamic> dataFromSharedPref = {};
// A task that needs some time to load e.g. Getting data from SharedPreference
// TODO: Change this part to load from your SharedPreference
await Future.delayed(const Duration(seconds: 1), () {
dataFromSharedPref = {
"2022-04-08 15:49:41.864929": "1234567",
"2022-04-08 15:49:55.392684": "1234567"
};
});
return dataFromSharedPref;
}
return FutureBuilder(
future: _loadData(),
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
// Show loading when there is no data
return const Center(child: CircularProgressIndicator());
} else {
// Build the list when data is received
var myData = snapshot.data;
return ListView.builder(
itemCount: myData.length,
itemBuilder: (BuildContext context, int index) {
String key = myData.keys.elementAt(index);
return ListTile(
title: Text('Key: $key'),
subtitle: Text('Value: ${myData[key]}'),
);
});
}
});
}
}