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?