Advertisement
nic0501

Flutter Favorites

May 22nd, 2022 (edited)
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 9.29 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2.  
  3. void main() {
  4.   runApp(const MyApp());
  5. }
  6.  
  7. class MyApp extends StatelessWidget {
  8.   const MyApp({Key? key}) : super(key: key);
  9.  
  10.   // This widget is the root of your application.
  11.   @override
  12.   Widget build(BuildContext context) {
  13.     return const MaterialApp(
  14.       debugShowCheckedModeBanner: false,
  15.       home: CupertinoBottomNav(),
  16.     );
  17.   }
  18. }
  19.  
  20.  
  21. // My Bottom Navigation Bar:
  22. class CupertinoBottomNav extends StatelessWidget {
  23.   const CupertinoBottomNav({Key? key}) : super(key: key);
  24.  
  25.   @override
  26.   Widget build(BuildContext context) {
  27.     return CupertinoTabScaffold(
  28.       tabBar: CupertinoTabBar(
  29.         items: const [
  30.           BottomNavigationBarItem(
  31.               icon: Icon(
  32.                 Icons.home_filled,
  33.                 size: 28,
  34.               ),
  35.               label: 'Home'),
  36.           BottomNavigationBarItem(
  37.               icon: Icon(
  38.                 Icons.storage_rounded,
  39.                 size: 28,
  40.               ),
  41.               label: 'Favorites'),
  42.         ],
  43.       ),
  44.       tabBuilder: (context, index) {
  45.         switch (index) {
  46.           case 0:
  47.             return CupertinoTabView(builder: (context) => const ListPage());
  48.           case 1:
  49.           default:
  50.             return CupertinoTabView(builder: (context) => const Favorites());
  51.         }
  52.       },
  53.     );
  54.   }
  55. }
  56.  
  57.  
  58. // This is my model class of the items which get stored as favorites
  59.  
  60. class TestItems {
  61.   String name;
  62.   int id;
  63.  
  64.   TestItems({required this.name, required this.id});
  65.  
  66.   factory TestItems.fromJson(Map<String, dynamic> json) {
  67.     return TestItems(
  68.       name: json['name'] as String,
  69.       id: json['id'] as int,
  70.     );
  71.   }
  72.  
  73.   Map<String, dynamic> toMap() {
  74.     return {
  75.       'id': id,
  76.       'name': name,
  77.     };
  78.   }
  79. }
  80.  
  81.  
  82. // This is the page where the stored favorite items are displayed.
  83. //You will see that it only refreshes the page when I restart the app.
  84. //I think this is caused by the CupertinoBottomNavigationBar as it works properly with the Material on.
  85. // But I would like to keep the CupertinoBar as I want it to be shown on every page
  86.  
  87. // Thank you so much for you support!!!
  88.  
  89. class Favorites extends StatefulWidget {
  90.   const Favorites({Key? key}) : super(key: key);
  91.  
  92.   @override
  93.   _FavoritesState createState() => _FavoritesState();
  94. }
  95.  
  96. class _FavoritesState extends State<Favorites> {
  97.   // ignore: prefer_typing_uninitialized_variables
  98.   var database;
  99.   List<TestItems> items = <TestItems>[];
  100.  
  101.   Future initDb() async {
  102.     database = await openDatabase(
  103.       join(await getDatabasesPath(), 'person_database.db'),
  104.       onCreate: (db, version) {
  105.         return db.execute(
  106.           "CREATE TABLE person(id INTEGER PRIMARY KEY,  name TEXT)",
  107.         );
  108.       },
  109.       version: 1,
  110.     );
  111.  
  112.     getMechanism().then((value) {
  113.       setState(() {
  114.         items = value;
  115.       });
  116.     });
  117.   }
  118.  
  119.   Future<List<TestItems>> getMechanism() async {
  120.     final Database db = await database;
  121.  
  122.     final List<Map<String, dynamic>> maps = await db.query('person');
  123.     return List.generate(maps.length, (i) {
  124.       return TestItems(
  125.         id: maps[i]['id'],
  126.         name: maps[i]['name'] as String,
  127.       );
  128.     });
  129.   }
  130.  
  131.   Future<void> deleteDB(int id) async {
  132.     final db = await database;
  133.     await db.delete(
  134.       'person',
  135.       where: "id = ?",
  136.       whereArgs: [id],
  137.     );
  138.   }
  139.  
  140.   // Future<void> updateDB(Mechanism person) async {
  141.   //   final db = await database;
  142.  
  143.   //   await db.update(
  144.   //     'person',
  145.   //     where: "id = ?",
  146.   //     whereArgs: [person.id],
  147.   //   );
  148.   // }
  149.  
  150.   @override
  151.   void initState() {
  152.     super.initState();
  153.     initDb();
  154.   }
  155.  
  156.   @override
  157.   Widget build(BuildContext context) {
  158.     return Scaffold(
  159.       appBar: AppBar(
  160.         title: const Text("Favorites"),
  161.       ),
  162.       body: ListView.builder(
  163.           itemCount: items.length,
  164.           itemBuilder: (context, index) {
  165.             var item = items[index];
  166.             return ListTile(
  167.               title: Text(
  168.                 item.name,
  169.               ),
  170.               onTap: () {
  171.                 Navigator.push(
  172.                   context,
  173.                   MaterialPageRoute(
  174.                       builder: (context) => ItemDtl(items: item, id: index)),
  175.                 );
  176.               },
  177.               trailing: IconButton(
  178.                 color: Colors.red,
  179.                 icon: const Icon(Icons.delete_forever_rounded),
  180.                 onPressed: () {
  181.                   deleteDB(item.id).then((value) {
  182.                     getMechanism().then((value) {
  183.                       setState(() {
  184.                         items = value;
  185.                       });
  186.                     });
  187.                   });
  188.                 },
  189.               ),
  190.             );
  191.           }),
  192.     );
  193.   }
  194. }
  195.  
  196.  
  197. // This is the Detailpage of the items
  198.  
  199. class ItemDtl extends StatefulWidget {
  200.   const ItemDtl({Key? key, required this.items, required this.id})
  201.       : super(key: key);
  202.  
  203.   final TestItems items;
  204.   final int id;
  205.  
  206.   @override
  207.   _ItemDtlState createState() => _ItemDtlState();
  208. }
  209.  
  210. class _ItemDtlState extends State<ItemDtl> {
  211.   // ignore: prefer_typing_uninitialized_variables
  212.   var database;
  213.  
  214.   @override
  215.   void initState() {
  216.     super.initState();
  217.  
  218.     initDb();
  219.   }
  220.  
  221.   Future initDb() async {
  222.     database = openDatabase(
  223.       join(await getDatabasesPath(), 'person_database.db'),
  224.       onCreate: (db, version) {
  225.         return db.execute(
  226.           "CREATE TABLE person(id INTEGER PRIMARY KEY,  name TEXT, height TEXT, mass TEXT, hair_color TEXT, skin_color TEXT, eye_color TEXT, birth_year TEXT, gender TEXT)",
  227.         );
  228.       },
  229.       version: 1,
  230.     );
  231.   }
  232.  
  233.   Future<void> insertEntry(TestItems items) async {
  234.     final Database db = await database;
  235.  
  236.     await db.insert(
  237.       'person',
  238.       items.toMap(),
  239.       conflictAlgorithm: ConflictAlgorithm.replace,
  240.     );
  241.   }
  242.  
  243.   Future<void> updateDB(TestItems items) async {
  244.     final db = await database;
  245.  
  246.     await db.update(
  247.       'person',
  248.       items.toMap(),
  249.       where: "id = ?",
  250.       whereArgs: [items.id],
  251.     );
  252.   }
  253.  
  254.   @override
  255.   Widget build(BuildContext context) {
  256.     return Scaffold(
  257.       appBar: AppBar(
  258.         centerTitle: true,
  259.         title: Text(widget.items.name),
  260.       ),
  261.       body: Padding(
  262.         padding: const EdgeInsets.all(8.0),
  263.         child: ListView(children: <Widget>[
  264.           TextButton.icon(
  265.             icon: const Icon(Icons.storage),
  266.             label: const Text(
  267.               "Add To Favorites",
  268.             ),
  269.             onPressed: () {
  270.               insertEntry(widget.items);
  271.             },
  272.           ),
  273.           Text(
  274.             "Name: ${widget.items.name}",
  275.           ),
  276.         ]),
  277.       ),
  278.     );
  279.   }
  280. }
  281.  
  282. // This is the page where user is albe to store individuall list items as favorites.
  283.  
  284. class ListPage extends StatefulWidget {
  285.   const ListPage({Key? key}) : super(key: key);
  286.  
  287.   @override
  288.   _ListPageState createState() => _ListPageState();
  289. }
  290.  
  291. class _ListPageState extends State<ListPage> {
  292.   TextEditingController searchController = TextEditingController();
  293.   List<TestItems> shownList = <TestItems>[
  294.     TestItems(name: 'Test', id: 1),
  295.     TestItems(name: 'Test2', id: 2),
  296.     TestItems(name: 'Test3', id: 3)
  297.   ];
  298.   List<TestItems> initialData = <TestItems>[
  299.     TestItems(name: 'Test', id: 1),
  300.     TestItems(name: 'Test2', id: 2),
  301.     TestItems(name: 'Test3', id: 3)
  302.   ];
  303.  
  304.   void queryPeople(String queryString) {
  305.     if (kDebugMode) {
  306.       print("queryString = $queryString");
  307.     }
  308.  
  309.     setState(() {
  310.       shownList = initialData.where((string) {
  311.         if (string.name.toLowerCase().contains(queryString.toLowerCase())) {
  312.           return true;
  313.         } else {
  314.           return false;
  315.         }
  316.       }).toList();
  317.     });
  318.   }
  319.  
  320.   @override
  321.   Widget build(BuildContext context) {
  322.     return Scaffold(
  323.       appBar: AppBar(
  324.         title: const Text('Detail'),
  325.       ),
  326.       body: Column(
  327.         children: <Widget>[
  328.           TextButton.icon(
  329.             label: const Text('Favorites'),
  330.             icon: const Icon(
  331.               Icons.storage,
  332.             ),
  333.             onPressed: () {
  334.               Navigator.push(
  335.                 context,
  336.                 MaterialPageRoute(builder: (context) => const Favorites()),
  337.               );
  338.             },
  339.           ),
  340.           Expanded(
  341.             child: ItemList(
  342.               item: shownList,
  343.             ),
  344.           ),
  345.         ],
  346.       ),
  347.     );
  348.   }
  349. }
  350.  
  351. class ItemList extends StatelessWidget {
  352.   final List<TestItems> item;
  353.  
  354.   const ItemList({Key? key, required this.item}) : super(key: key);
  355.  
  356.   @override
  357.   Widget build(BuildContext context) {
  358.     return ListView.builder(
  359.       itemCount: item.length,
  360.       itemBuilder: (context, index) {
  361.         var items = item[index];
  362.         var name = items.name;
  363.         return ListTile(
  364.           title: Text(
  365.             name,
  366.           ),
  367.           onTap: () {
  368.             items.id = index;
  369.             Navigator.push(
  370.               context,
  371.               MaterialPageRoute(
  372.                   builder: (context) => ItemDtl(
  373.                         id: index,
  374.                         items: items,
  375.                       )),
  376.             );
  377.           },
  378.         );
  379.       },
  380.     );
  381.   }
  382. }
  383.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement