我正在使用共享首选项在我的 flutter 应用程序中存储书签。有一个列表视图可将项目标记为收藏夹,还有一个书签屏幕显示所有已保存的项目。问题是,当我从列表视图中为某个项目添加书签时,除非我从书签屏幕中删除其中一个项目,否则它不会显示在书签屏幕中。只有这样列表才会刷新并正确显示。书签页面似乎不会在每次打开时刷新,只有当按下先前可用的书签项目上的删除图标时才会重新加载。
书签屏幕
class BookmarkScreen extends StatefulWidget {
BookmarkScreen({Key? key}) : super(key: key);
@override
State<BookmarkScreen> createState() => _BookmarkScreenState();
}
class _BookmarkScreenState extends State<BookmarkScreen> {
late SharedPreferenceManager _sharedPreferenceManager;
late DatabaseManager _databaseManager;
late List<Bookmark> bookmarks = [];
@override
void initState() {
super.initState();
_sharedPreferenceManager =
Provider.of<SharedPreferenceManager>(context, listen: false);
_databaseManager = Provider.of<DatabaseManager>(context, listen: false);
print("hello");
_loadBookmarks();
setState(() {
});
}
Future<void> _loadBookmarks() async {
List<Bookmark> loadedBookmarks = await BookmarkManager.getBookmarks();
setState(() {
bookmarks = loadedBookmarks;
});
}
Future<void> _deleteBookmark(Bookmark bookmarkToDelete) async {
await BookmarkManager.deleteBookmark(bookmarkToDelete);
_loadBookmarks();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Bookmark Screen")),
body: ListView.builder(
itemCount: bookmarks.length,
itemBuilder: (context, index) {
final Bookmark currentItem = bookmarks[index];
return _listItemView(index, bookmarks[index].surahName ,
bookmarks[index].verseNo.toString(),currentItem);
},
),
);
}
Widget _listItemView(
int index,
String title,
String verseSubtitle,
Bookmark currentItem,
{String fontFamily: 'QCF'}) {
return ListTile(
tileColor: index % 2 == 0
? !_sharedPreferenceManager.isDarkModeOn
? ColorConstants.secondaryColor
: ColorConstants.Dark_Grey
: !_sharedPreferenceManager.isDarkModeOn
? Colors.white
: ColorConstants.Light_Grey,
title: Text(
title,
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w600,
),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 7,
),
Text(verseSubtitle,
style: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w400,
)),
]),
trailing: IconButton(
icon: Icon(Icons.delete), onPressed: () { _deleteBookmark(currentItem) ;},
),
);
}
}
书签管理器
class BookmarkManager {
static const _key = 'bookmarks';
static Future<List<Bookmark>> getBookmarks() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final String? storedData = prefs.getString(_key);
if (storedData != null) {
final Iterable decoded = json.decode(storedData);
return decoded.map((bookmark) => Bookmark.fromMap(bookmark)).toList();
}
return [];
}
static Future<void> saveBookmarks(List<Bookmark> bookmarks) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final String encoded = json.encode(bookmarks.map((bookmark) => bookmark.toMap()).toList());
print(encoded);
prefs.setString(_key, encoded);
}
static Future<void> addBookmark(Bookmark newBookmark) async {
List<Bookmark> bookmarks = await getBookmarks();
if(bookmarks.contains(newBookmark))
{
print(bookmarks.length);
}
else{
bookmarks.add(newBookmark);
print(bookmarks.length);
await saveBookmarks(bookmarks);
}
}
static Future<void> deleteBookmark(Bookmark bookmarkToDelete) async {
List<Bookmark> bookmarks = await getBookmarks();
bookmarks.removeWhere((bookmark) =>
bookmark.surahNo== bookmarkToDelete.surahNo && bookmark.verseNo==bookmarkToDelete.verseNo);
await saveBookmarks(bookmarks);
}
}
您可以用
FutureBuilder
来包装您的内容
class _MyHomePageState extends State<MyHomePage> {
Future<void> _refresh() async {
// Fetch data from Shared Preferences again
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _refresh(), // Use your refresh function here
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else {
// Display your page content here
return PlaceHolder();
}
},
),
);
}
}