Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to save and read a list called "teams" as a shared_preference so every time I switch back to this screen and take a look at my teams list it isn't empty and shows the old values.

Here is my code:

Dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

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

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

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

  void addTeam(String name) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(() {
      teams.add(name);
    });
    Navigator.of(context).pop();

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

  void newTeam() {
    showDialog<AlertDialog>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Name auswählen: '),
          content: TextField(
            onSubmitted: addTeam,
          ),
        );
      },
    );
  }

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

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

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 22),
      child: ListTile(
        leading: Icon(Icons.sports_volleyball_outlined),
        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(),
        ),
      ),
    );
  }
}


What I have tried:

No matter how I set it up it doesn't seem to work. Then I come back the list is empty. Do you guys have any ideas?
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900