简体   繁体   中英

Flutter - setState not updating a List inside a ListView.separated

I am saving a list of favorites in my game app, I can add or remove games from the list, but on the removeFavorite method, when I use setState in " games.remove(index) " the listview.separeted doesn't update. If close and open favorite screen, the list is updated but while I am at the favorite screen it doesn't update.

class _FavoriteScreenState extends State<FavoriteScreen> {

  List<dynamic> favoriteList = [];
  List<Game> games = [];

  @override
  void initState() {

    loadFavorites();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    Widget _buildListView(Game game, int index){

      return InkWell(
        child: Container(
          height: 80,
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                margin: EdgeInsets.only(left: 5),
                  child: Image.network(game.cover),
                ),
              ),
              Expanded(
                flex: 2,
                child: Container(
                  child: Row(
                    children: <Widget>[
                      SizedBox(width: 15,),
                      Text(
                          game.title,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.w300,
                          fontSize: 14
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        onLongPress: (){
          _showDialog(index);
        },
      );

    }

    return Scaffold(
      backgroundColor: Theme.of(context).backgroundColor,
      appBar: AppBar(
        title: Text("Favorites"),
      ),

      body: Container(

        margin: EdgeInsets.fromLTRB(16, 16, 16, screenHeight > 720 ? 90 : 62),
        child: ListView.separated(
          separatorBuilder: (BuildContext context, int index) => Divider(color: Colors.black,),
          itemCount: games.length,
            itemBuilder: (context, index){

              return _buildListView(games[index], index);

            },
        )
      ),

    );
  }

  Future<File> getFile() async{

    final directory = await getApplicationDocumentsDirectory();
    return File("${directory.path}/favorites.json");

  }

  Future<String> readFavorite() async{

    try{

      // Le e retorna o arquivo como String
      final file = await getFile();
      return file.readAsString();

    } catch (e){
      return null;
    }


  }

  void loadFavorites() {

    readFavorite().then((data){

      // Transforma o arquivo JSON numa List
      favoriteList = json.decode(data);


      if(favoriteList.length > 0 && favoriteList != null){

        favoriteList.forEach((map){

          Game game = Game(map["cover"], map["title"], map["description"], map["url"]);

          setState(() {
            games.add(game);
          });


        });

      } else {

      }

      print(games.length);

    });


  }

  Future<File> saveFile() async{

    String data = json.encode(favoriteList);

    final file = await getFile();

    return file.writeAsString(data);

  }

  void _showDialog(int index){

    showDialog(
        context: context,
        builder: (BuildContext context){
          return AlertDialog(
            content: Text("?",
              style: TextStyle(fontSize: 18) ,),
            actions: <Widget>[
              FlatButton(
                  child: Text("YES"),
                  onPressed: (){
                    Navigator.of(context).pop();
                    removeFavorite(index);

                  }
              ),
              FlatButton(
                  child: Text("NO"),
                  onPressed: (){
                    Navigator.of(context).pop();
                  }
              ),
            ],
          );
        }
    );

  }

  void removeFavorite(int index){

    favoriteList.forEach((m) {
      Map<String, dynamic> map = m;

      if (map.containsValue(games[index].title)) {
        favoriteList.remove(m);

        saveFile();
        setState(() {
          games.remove(index);
        });

      }
    });

  }

}

My bad, I replaced the remove with removeAt and it worked.

setState(() {
  games.removeAt(index);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM