Untitled

mail@pastecode.io avatar
unknown
dart
3 years ago
2.6 kB
4
Indexable
Never
//this button should call on the notifiermethods to update favorites

IconButton(
    icon: listOfFavorites.contains(widget.buildingMaterial.title)
        ? Icon(Icons.favorite)
        : Icon(Icons.favorite_outline),
    onPressed: () {
      if (listOfFavorites.contains(widget.buildingMaterial.title)) {
        setState(() {
          while (listOfFavorites
              .contains(widget.buildingMaterial.title)) {
            listOfFavorites.remove(widget.buildingMaterial.title);
          }

          WriteAndRead().writeToFile(listOfFavorites);
        });
      } else {
        setState(() {
          listOfFavorites.add(widget.buildingMaterial.title);
        });

        WriteAndRead().writeToFile(listOfFavorites);
      }
    }),

//these methods should update the info sent to favorites

class WriteAndRead with ChangeNotifier {
  String titleString = "";

  writeToFile(List<String> list) async {
    final Directory directory = await getApplicationDocumentsDirectory();
    final File file = File('${directory.path}/favorites.txt');
    titleString = await file.readAsString();
    if (listOfFavorites.join(";") != titleString) {
      writeToFileEmpty();
      for (String title in list) {
        await file.writeAsString(title + ";", mode: FileMode.append);
      }
    }
    notifyListeners();
  }

  readFromFile() async {
    try {
      final Directory directory = await getApplicationDocumentsDirectory();
      final File file = File('${directory.path}/favorites.txt');
      titleString = await file.readAsString();
    } catch (e) {
      print("Couldn't read file");
    }
    listOfFavorites = titleString.split(";");
    for (String title in listOfFavorites) {
      print(title);
    }
  }

  writeToFileEmpty() async {
    final Directory directory = await getApplicationDocumentsDirectory();
    final File file = File('${directory.path}/favorites.txt');
    file.writeAsStringSync('');
    notifyListeners();
  }
}

//This widget should update

class Favorites extends StatefulWidget {
  List<Event> eventList;

  Favorites(this.eventList);

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

class _FavoritesState extends State<Favorites> {
  @override
  Widget build(BuildContext context) {
    return Consumer<WriteAndRead>(
        builder: (context, writeandread, child) => Center(
              child: Text(
                writeandread.titleString,
                style: TextStyle(color: Colors.purple),
              ),
            ));
  }
}