1

I state that I am a novice in flutter and dart. I followed both tutorials on the official site to create a first example.

Later, to explore the world of flutter a bit, I tried to implement the deletion of a list item that I have previously saved. Initially the problem is the one reported in this question asked a couple of years ago.

Following the advice given in the accepted answer, I got the following complete code:

import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

Set<WordPair> _savedPair = <WordPair>{};

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: const RandomWords());
  }
}

class RandomWords extends StatefulWidget {
  const RandomWords({Key? key}) : super(key: key);

  @override
  _RandomWordsState createState() => _RandomWordsState();
}

class _RandomWordsState extends State<RandomWords> {
  final _suggestions = <WordPair>[];
  final _biggerFont = const TextStyle(fontSize: 18.0);

  Widget _buildSuggestions() {
    return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemBuilder: (context, i) {
        if (i.isOdd) return const Divider();

        final index = i ~/ 2;
        if (index >= _suggestions.length) {
          _suggestions.addAll(generateWordPairs().take(10));
        }

        return _buildRow(_suggestions[index], index);
      },
    );
  }

  Widget _buildRow(WordPair pair, int index) {
    final alreadySaved = _savedPair.contains(pair);
    return ListTile(
      title: Text(
        " ${pair.asPascalCase} - $index",
        style: _biggerFont,
      ),
      trailing: Icon(
        alreadySaved ? Icons.favorite : Icons.favorite_border,
        color: alreadySaved ? Colors.red : null,
        semanticLabel: alreadySaved ? 'Removed from saved ' : 'Save',
      ),
      onTap: () {
        setState(() {
          if (alreadySaved) {
            _savedPair.remove(pair);
          } else {
            _savedPair.add(pair);
          }
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Startup Name Generator'),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.list),
            onPressed: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => const SavedPage()
                  )
              );
            },
          ),
        ],
      ),
      body: _buildSuggestions(),
    );
  }
}

class SavedPage extends StatefulWidget {
  const SavedPage({Key? key}) : super(key: key);

  @override
  _SavedPageState createState() => _SavedPageState();
}

class _SavedPageState extends State<SavedPage> {
  @override
  Widget build(BuildContext context) {
    final tiles = _savedPair.map(
      (pair) {
        return ListTile(
          title: Text(pair.asPascalCase,
              style: const TextStyle(
                fontSize: 18.0,
              )),
          subtitle: Row(children: <Widget>[
            RawMaterialButton(
                onPressed: () {
                  _remove(pair);
                },
                elevation: 2.0,
                fillColor: Colors.red,
                child: const Icon(Icons.remove, size: 18.0),
                shape: const CircleBorder()),
            const Text('Remove me'),
          ]),
          trailing: const Icon(Icons.done),
        );
      },
    );
    final divided = tiles.isNotEmpty
        ? ListTile.divideTiles(
            context: context,
            tiles: tiles,
          ).toList()
        : <Widget>[];

    return Scaffold(
        appBar: AppBar(
          title: const Text('Saved Suggestions'),
        ),
        body: ListView(children: divided));
  }

  void _remove(WordPair pairToRemove) {
    setState(() {
      if (_savedPair.contains(pairToRemove)) {
        _savedPair.remove(pairToRemove);
      }
    });
  }
}

The problem I have is that when I run the function _remove() actually the WordPair pairToRemove is removed from the globally defined Set _savedPair, but when I go back to the home page RandomWords(), the icon with the full red heart (Icons.favorite) remains active in the WordPairs that I had previously selected. The icon returns to normal ( Icons.favorite_border) when I select / deselect any other item from the list to add / remove it from the saved ones.

It seems that, although _savedPair is global, it doesn't get updated immediately when I go back to the homepage. Does anyone have any idea where I'm doing wrong? Or, is there a cleaner alternative to avoid the declaration of _savedPair global?

Elidor00
  • 881
  • 10
  • 22

1 Answers1

3

Modify the onPressed button function to this:

    onPressed: () async {
      await Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => const SavedPage()
          )
      );
setState(()=>{});
    },
Eric Aig
  • 582
  • 1
  • 10
  • 14
  • It works, thanks! But I need to understand two things: why when I use the Navigator do I have to use `async` and `await` and why do I have to call the `setState(() {})` if I already use it whenever I change the global variable `_savedPair`? – Elidor00 Jan 28 '22 at 13:04
  • 1
    Navigator.push is as you can guess returns a Future that's only completed when the root *B* you are pushing to is popped from history and back to route *A*. This is also useful if you want to pass data from route B back to A. Check this out: https://medium.com/flutter-community/flutter-push-pop-push-1bb718b13c31 scroll down to the "Where is the data?" section and you can enlighten yourself more on how passing datas work. – Eric Aig Jan 30 '22 at 06:45
  • 1
    If I understand your code correctly, the setState you are calling after each changes to _savedPair only affects the SavedPage widget. According to the setState documentation, `Notify the framework that the internal state of this object has changed.`. Notice the use of *this object*, in your case would be `SavedPage` not `RandomWords()`. What this means is that you are not really refreshing the `RandomWords()` widget instead it's the `SavedPage()'s`. That's why it makes sense to await for savedPage to pop from history and then refresh `RandomWords()` using it's own `setState()` (*this object*) – Eric Aig Jan 30 '22 at 06:54
  • 1
    https://api.flutter.dev/flutter/widgets/State/setState.html – Eric Aig Jan 30 '22 at 06:54