如何在Flutter中实现列表收藏功能并在专属Tab页展示收藏内容?
完整修改后代码
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: HomeScreen(), ); } } class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => AnaEkran(); } // 新增数据实体类,存储条目名称和收藏状态 class FruitItem { final String name; bool isFavorited; FruitItem({required this.name, this.isFavorited = false}); } class AnaEkran extends State<HomeScreen> { final List<FruitItem> mainDataList = [ FruitItem(name: "Apple"), FruitItem(name: "Apricot"), FruitItem(name: "Banana"), FruitItem(name: "Blackberry"), FruitItem(name: "Coconut"), FruitItem(name: "Date"), FruitItem(name: "Fig"), FruitItem(name: "Gooseberry"), FruitItem(name: "Grapes"), FruitItem(name: "Lemon"), FruitItem(name: "Litchi"), FruitItem(name: "Mango"), FruitItem(name: "Orange"), FruitItem(name: "Papaya"), FruitItem(name: "Peach"), FruitItem(name: "Pineapple"), FruitItem(name: "Pomegranate"), FruitItem(name: "Starfruit") ]; @override Widget build(BuildContext context) { // 过滤出收藏的条目 final favoritedList = mainDataList.where((item) => item.isFavorited).toList(); return DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( title: const Text('NickName Generator'), backgroundColor: Colors.deepPurple, bottom: const TabBar( tabs: [ Tab(icon: Icon(Icons.article_rounded)), Tab(icon: Icon(Icons.favorite)), ], ), ), // 用TabBarView区分两个Tab的页面内容 body: TabBarView( children: [ // 第一个Tab:全部内容列表 ListView.builder( itemCount: mainDataList.length, itemBuilder: (context, index) { final currentItem = mainDataList[index]; return Card( child: Padding( padding: const EdgeInsets.all(20.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( currentItem.name, style: const TextStyle(fontSize: 19.0), ), // 收藏按钮 IconButton( onPressed: () { setState(() { currentItem.isFavorited = !currentItem.isFavorited; }); }, icon: Icon( currentItem.isFavorited ? Icons.favorite : Icons.favorite_border, color: currentItem.isFavorited ? Colors.red : null, ), ) ], ), ), ); }, ), // 第二个Tab:仅收藏内容列表 ListView.builder( itemCount: favoritedList.length, itemBuilder: (context, index) { final currentItem = favoritedList[index]; return Card( child: Padding( padding: const EdgeInsets.all(20.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( currentItem.name, style: const TextStyle(fontSize: 19.0), ), IconButton( onPressed: () { setState(() { currentItem.isFavorited = false; }); }, icon: const Icon(Icons.favorite, color: Colors.red), ) ], ), ), ); }, ) ], ), ), ); } }
核心改动说明
- 新增
FruitItem实体类,同时存储条目的名称和收藏状态 - 替换原有的单一ListView为
TabBarView,分别对应全部列表和收藏列表两个页面 - 每个列表项末尾新增收藏按钮,点击自动切换当前条目的收藏状态,已收藏的条目会显示红色实心收藏图标
- 收藏页列表自动过滤,仅展示已标记为收藏的条目,在收藏页点击收藏按钮也可以直接取消收藏、移除对应条目
内容的提问来源于stack exchange,提问作者Aleyna Eser
相关产品推荐
相关产品推荐

