如何在 Flutter 中为 Listtile 从地图中检索数据

how to retrieve data from map for Listtile in flutter

我想从我从 sharedpreference 收到的地图接收数据。

数据如下所示:

{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}

日期是关键,数字是价值。 现在我需要在 4 个列表块中显示所有 4 个键和值。 这怎么可能? 我真的是 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);
  }```

我在这里举了一个粗略的例子。
您可以在 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]}'),
                  );
                });
          }
        });
  }
}