使用共享首选项保存字符串和关联图标

save string and associated icon with shared prefs

我目前正在使用共享首选项来保存字符串列表。每次打开页面时,对于列表中的每个字符串条目,我都会在列表视图中创建一个列表图块。但是现在我不想只保存字符串,我什至想用它保存一个图标。但是我完全不知道如何解决这个问题

这是我当前的代码:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:trainings_app/widgets/alertbox_widget.dart';
import 'package:trainings_app/widgets/team_widget.dart';

class TeamScreen extends StatefulWidget {
  @override
  _TeamScreenState createState() => _TeamScreenState();
}

class _TeamScreenState extends State<TeamScreen> {
  late SharedPreferences sharedPreferences;
  List<String> teams = [];

  IconData? currentIcon;

  @override
  void initState() {
    tryFetchData();
    super.initState();
  }

  void tryFetchData() async {
    sharedPreferences = await SharedPreferences.getInstance();
    if (!sharedPreferences.containsKey('teams')) {
      sharedPreferences.setStringList('teams', []);
      return;
    }
    teams = sharedPreferences.getStringList('teams') as List<String>;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: teams.length,
        itemBuilder: (context, index) {
          return Team(
            teams[index],
            Icon(currentIcon),
            () => removeTeam(teams[index]),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          newTeam();
        },
        child: Icon(
          CupertinoIcons.add,
        ),
      ),
    );
  }

  void newTeam() {
    showDialog<Alertbox>(
      context: context,
      builder: (BuildContext context) {
        return Alertbox('Namen auswählen:', addTeam);
      },
    );
  }

  void addTeam(String name, IconData? icon) {
    if (name.isNotEmpty) {
      setState(() {
        currentIcon = icon;
        teams.add(name);
      });
    }

    Navigator.pop(context);
    sharedPreferences.setStringList('teams', teams);
  }

  void removeTeam(String name) {
    setState(() {
      teams.remove(name);
    });

    sharedPreferences.setStringList('teams', teams);
  }
}

class Team extends StatelessWidget {
  final String name;
  final Icon icon;
  final Function remove;
  const Team(this.name, this.icon, this.remove);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 22),
      child: ListTile(
        leading: Icon(icon.icon),
        contentPadding: EdgeInsets.symmetric(vertical: 8.0),
        title: Text(
          name,
          style: TextStyle(
            fontSize: 18.0,
            fontWeight: FontWeight.w600,
          ),
        ),
        trailing: IconButton(
          icon: Icon(CupertinoIcons.delete),
          onPressed: () => remove(),
        ),
        onTap: () {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => TeamWidget(name, icon)));
        },
      ),
    );
  }
}

您可以使用每个图标特定的 id 而不是 IconData 并将其存储为 Json:

的列表
Json.encode({title:"test", icon:61668}

然后保存到sharedPref。之后你可以按如下方式回忆它:

Icon(IconData(**YOUR SELECTED ID**, fontFamily: 'MaterialIcons'));

在此处查看每个图标的 ID:link


另一种解决方案是使用图像而不是图标!或使用this site将图像转换为字体图标并按如下方式使用:

Icon(IconData(int.parse('0x${e90a}',
    fontFamily: 'family name given in the link above'));