Click here to Skip to main content
15,921,841 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone here's my test app and I have some problems with making a Favorite page section where you can tap on button and add the item into fav page. I'm receiving a data from API and implementing it by Listview.builder

In main.dart, I'm openning a box called 'favorites_box'
in ListViewAPI(), I've added the elements which I tap to the box('favorites_box'):
and I've created a list, and tried to save the elements from box named "favorites_box" and got data which was added while I tap favorite IconButton but without success.

Below is my code,

I'll be grateful if someone could help me with this problem, as I'm trying to fix this issue for a couple of days P.s. I'm so sorry for some inconveniences, I'm a novice yet that's why hope you'll understand me Thanks!

What I have tried:

HERE'S A CODE:
main.dart, here I'm openning a box called 'favorites_box'

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
 
 
void main() async{
  await GetStorage.init();
  await Hive.initFlutter();
  await Hive.openBox('favorites_box');
  runApp(MainPage());
}
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: '/',
      getPages: [
        GetPage(name: '/', page: () => MyApp()),
        GetPage(name: '/main-page', page: () => MainPage()),
        GetPage(name: '/favorite_page', page: () => FavoritePage()),
        // Dynamic route
      ],
      home: MainPage(),
    );
  }
}


Well here's a code of home page: main_page.dart

import 'package:flutter/material.dart';
import '../View/listview_api.dart';
    
class MainPage extends StatefulWidget {
  @override
  State<MainPage> createState() => _MainPageState();
}
 
class _MainPageState extends State<MainPage> {
  int currentIndex = 0;
 
  List<BottomNavigationBarItem>? items;
 
  final screens = [
    HomePage(),
    HomePage()
    FavoritePage(),
    HomePage()
  ];
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.white,
            title: Container(
              width: double.infinity,
              height: 40,
              color: Colors.white,
              child: Center(
                child: TextField(
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
 
                    ),
                      hintText: 'Searching',
                      prefixIcon: Icon(Icons.search),
                      suffixIcon: Icon(Icons.notifications)),
                ),
              ),
            ),
          ),
          body: screens[currentIndex],
          bottomNavigationBar: BottomNavigationBar(
          unselectedItemColor: Colors.grey,//AppColors.unselectedBottomNavItem,
          selectedItemColor: Colors.blue,//AppColors.assets,
          onTap: (index) => setState(() {
            currentIndex = index;
          }),//controller.setMenu(BottomMenu.values[pos]),
          //currentIndex: ,//controller.bottomMenu.index,
          type: BottomNavigationBarType.fixed,
          backgroundColor: Colors.white,
          currentIndex: currentIndex,
          selectedLabelStyle: const TextStyle(
            fontSize: 10,
            fontWeight: FontWeight.w500,
          ),
          unselectedLabelStyle: const TextStyle(
            fontSize: 10,
            fontWeight: FontWeight.w500,
          ),
          elevation: 8,
            items: [
              BottomNavigationBarItem(
                icon: Icon(Icons.home),
                label: 'Home',
                backgroundColor: Colors.blue,
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.add_shopping_cart),
                label: 'Shopping cart',
                backgroundColor: Colors.red,
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.favorite),
                label: 'Favorite',
                backgroundColor: Colors.green,
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.person),
                label: 'Profile',
                backgroundColor: Colors.yellow,
              ),
            ],
        ),
        ),
      ),
    );
  }
}
 
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Center(
          child: Padding(
            padding: EdgeInsets.all(10.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                //Image.asset('images/image0.jpg'),
                SizedBox(
                  height: 25.0,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'New!',
                      textAlign: TextAlign.left,
                      style: TextStyle(
                        fontSize: 25.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    IconButton(
                      onPressed: () {},
                      icon: Icon(
                        Icons.arrow_forward_outlined,
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 25.0,
                ),
                SizedBox(
                  height: 300.0,
                  width: double.infinity,
                  child: ListViewAPI(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


And now, below is a code of ListViewAPI(), here I've added the elements which I tap to the box('favorites_box'): listview_api.dart

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
 
String? stringResponse;
Map? mapResponse;
Map? dataResponse;
List? listResponse;
 
class ListViewAPI extends StatefulWidget {
  const ListViewAPI({Key? key}) : super(key: key);
 
  @override
  _ListViewAPIState createState() => _ListViewAPIState();
}
 
class _ListViewAPIState extends State<ListViewAPI> {
  Future apiCall() async {
    http.Response response;
    response = await http.get(Uri.parse("https://api.client.macbro.uz/v1/product"));
    if(response.statusCode == 200) {
      setState(() {
        //  stringResponse = response.body;
        mapResponse = jsonDecode(response.body);
        listResponse = mapResponse!['products'];
      });
    }
  }
 
  @override
  void initState() {
    super.initState();
    apiCall();
  }
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scrollbar(
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, index) {
              return Stack(
                children: [
                  Card(
                    child: Image.network(
                      listResponse![index]['image'],
                    ),
                  ),
                  Positioned(
                    right: 0,
                    child: InkWell(
                      child: IconButton(
                        onPressed: () async {
                          await Hive.box('favorites_box').put(listResponse![index]['image'], listResponse);
                        },
                        icon: Icon(
                          Icons.favorite_rounded,
                          color: Colors.red,
                        ),
                      ),
                    ),
                  ),
                ],
              );
            },
            itemCount: listResponse == null ? 0 : listResponse!.length,
          ),
        ),
    );
  }
}


So here, I created a list, and tried to save the elements from box named "favorites_box" and got data which was added while I tap favorite IconButton upper but without success( : favorite_page.dart

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_db/Models/products_model.dart';
import 'package:hive_flutter/hive_flutter.dart';
 
class FavoritePage extends StatelessWidget {
  List posts = List.from(Hive.box('favorites_box').values);
  var test;
  List<ProductModel> pm = ProductModel(test.image, test.name) as List<ProductModel>;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          test = ProductModel.fromJson(posts[index]);
          return Stack(
            children: [
              Card(
                child: Image.network(
                 // posts[index]['image'],
                   pm.map((prod) => ProductModel.fromJson(prod)).toList();
                ),
              ),
              Positioned(
                right: 0,
                child: InkWell(
                  child: IconButton(
                    onPressed: () async {
                      await Hive.box('favorites_box').delete(posts[index]);
                    },
                    icon: Icon(
                      Icons.favorite_rounded,
                      color: Colors.red,
                    ),
                  ),
                ),
              ),
            ],
          );
        },
        itemCount: posts == null ? 0 : posts.length,
      ),
    );
  }
}
Posted
Updated 5-May-22 1:31am
v4
Comments
Richard MacCutchan 5-May-22 6:43am    
Please add the relevant code to your question.
Member 15625382 5-May-22 6:53am    
code was below, but i can share once more https://pastebin.com/cSBnhwqG
Richard MacCutchan 5-May-22 7:05am    
No, I mean add the code to your question, not a link.
Member 15625382 5-May-22 7:31am    
Done it!)
wseng 7-May-22 5:43am    
try print out posts in FavoritePage, what you see in console?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900