简体   繁体   English

购物车页面的 Flutter Provider

[英]Flutter Provider for Cart page

I need to make a cart page for an e-commerce app.我需要为电子商务应用程序制作购物车页面。 where I am getting JSON data from API.我从 API 获取 JSON 数据的地方。 I can fetch the data and show data.我可以获取数据并显示数据。 but when it's matter to cart I cannot add this data to my provider page.但是当购物车很重要时,我无法将此数据添加到我的提供商页面。

This is MY Provider Page For Album这是我的专辑提供者页面

import 'package:flutter/material.dart';
import 'package:provider_test/albumModel.dart';
import '../Service/service.dart';

class MyStore extends ChangeNotifier {
  List<Album> _albums = [];
  List<Album> _busket = [];
  Album _activeAlbum = null;

  List<Album> get albums => _albums;
  List<Album> get buskets => _busket;
  Album get activeAlbum => _activeAlbum;
}

And this is my Album Model Page:这是我的专辑模型页面:

 import 'dart:convert';

import 'package:flutter/cupertino.dart';

List<Album> allalbumsFromJson(String str) {
  final jsonData = json.decode(str);
  return new List<Album>.from(jsonData.map((x) => Album.fromJson(x)));
} //ef

class AlbumList with ChangeNotifier {
  final List<Album> albums;

  AlbumList({
this.albums,
  });

  factory AlbumList.fromJson(List<dynamic> parsedJson) {
List<Album> albums = List<Album>();
albums = parsedJson.map((i) => Album.fromJson(i)).toList();

return AlbumList(albums: albums);
  }
  notifyListeners();
} //ef

class Album with ChangeNotifier {
  int userId;
  int id;
  String title;

  Album({this.userId, this.id, this.title});

  Album.fromJson(Map<String, dynamic> json) {
userId = json['userId'];
id = json['id'];
title = json['title'];
  }
  notifyListeners();
} //ef

Album albumFromJson(String str) {
final jsonData = json.decode(str);
return Album.fromJson(jsonData);
    } //ef

Now I can fetch Data Using this Function:现在我可以使用这个函数获取数据:

import 'package:flutter/cupertino.dart';
import 'package:provider_test/albumModel.dart';
import 'package:http/http.dart' as HTTP;

final url = ('https://jsonplaceholder.typicode.com/albums');

Future<List<Album>> getAllAlbum() async {
  final response = await http.get(url);
  // print(response.body);
  return allalbumsFromJson(response.body);
}

Future<Album> getAlbum() async {
  final response = await http.get('$url/1');
 return albumFromJson(response.body);
}

How Can I insert getAllAlbums() Data or you can say List Data into the _albums=[] which is situated in Mystore Page?我如何插入 getAllAlbums() 数据,或者您可以在位于 Mystore 页面的 _albums=[] 中说 List Data?

Hi for the cart I think you the best way you must use a map instead of a list like below:嗨,购物车,我认为您必须使用地图而不是如下列表的最佳方式:

  Map<int, FavoriteModel> _favoites = {};

  Map<int, FavoriteModel> get favoitesItem {
    return _favoites;
  }

And for adding data from you can use of this method:为了添加数据,您可以使用此方法:

  void addOrRemoveSingleItem({
    int foodId,
    String title,
    double price,
    String imageUrl,
    int userId
  }) async {
    if (_favoites.containsKey(foodId)) {
      try {
        final res = await http.post(
          addFavoriteUrl,
          body: {
            "user_id": userId.toString(),
            "food_id": foodId.toString(),
            "Is_delete": "1",
          },
        );
      } catch (e) {
        print(e);
        throw (e);
      }
    } else {
      try {
        _favoites.putIfAbsent(
          foodId,
          () => FavoriteModel(
            id: foodId,
            name: title,
            regularPrice: price,
            featureImage: imageUrl,
          ),
        );
        http.post(
          addFavoriteUrl,
          body: {
            "user_id": userId.toString(),
            "food_id": foodId.toString(),
          },
        );
      } catch (e) {
        print(e);
        throw (e);
      }
    }
    notifyListeners();
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用提供者 Flutter 的 Json 数组对象 - Json array object using provider Flutter 如何重定向到购物车网址页面 - How to redirect Add to cart url page 如何在颤振电子商务应用程序中将产品项目添加到购物车 - how to add product items to cart in flutter e commerce appication 结合使用jQuery和JSON在页面上显示购物车(无需刷新页面) - Using json with jQuery to display cart on the page (without a page refresh) 如何将带有对象的数组从提供程序传递到页面? - How pass array with objects from provider to page? 购物车错误:: 无法将商品添加到“购物车页面”:: 无法设置 null 的属性“textContent” - Shopping Cart Error :: Cannot add items to the “Shopping Cart Page ” :: Cannot set property 'textContent' of null Flutter 如何在带有提供程序的未来构建器中的 listview.builder 中显示数据 - Flutter How to show data in listview.builder inside future builder with provider 如何在 Flutter 应用程序中使用 SOLID 原则实现链接到提供者的 API 调用? - How to implement an API call linked to a Provider using SOLID principles in a Flutter app? Flutter andoid 模拟器在哪里使用path_provider将文件保存到Windows本地磁盘? - Where does Flutter andoid emulator save file to Windows local disk with path_provider? Flutter:打印列表如何来自提供商或将其作为邮件发送到 API 编辑#1 - Flutter : How can print list comes from provider or send it as post to API Edit #1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM