getter 'price' 没有为类型 'String' 定义

The getter 'price' isn't defined for the type 'String'

The getter 'id' isn't defined for the type 'String'.Try importing the library that defines 'id', correcting the name to the name of an existing getter, or defining a getter or field named >

我试图在使用购物车图标添加购物车商品时显示它们。当我单击购物车图标时,它会将我带到 CartScrren 页面,在那里它会显示所选项目。 但是我无法从我的购物车中获取值。

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/cart.dart'  ;
import '../widgets/cart_items_display.dart';

class CartScreen extends StatelessWidget {
 
  static const route = '/cart';

  @override
  Widget build(BuildContext context) {
    final cart = Provider.of<Cart>(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Text('Your Cart'),
      ),
      body: Column(
        children: <Widget>[
          Card(
            margin: EdgeInsets.all(25),
            child: Padding(
              padding: EdgeInsets.all(8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    'Total',
                    style: TextStyle(fontSize: 25),
                  ),
                  Spacer(),
                  Chip(
                    label: Text(
                      '$${cart.totalAmount}',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                    backgroundColor: Theme.of(context).primaryColor,
                  ),
                  TextButton(onPressed: () {}, child: Text('Order Now')),
                ],
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Expanded(
            child: ListView.builder(
              itemCount: cart.items.length,
              itemBuilder: (ctx, i) => CartItemDisplay(
              //Having problem Here**
               cart.items.values.toString()[i].id,
               cart.items.values.toString()[i].price,
               cart.items.values.toString()[i].quantity,
                cart.items.values.toString()[i].title,
                ///////**
              ),
            ),
          ),
        ],
      ),
    );
  }
}

下面是我的购物车这里我用的是这张地图

import 'package:flutter/foundation.dart';

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    required this.id,
    required this.title,
    required this.quantity,
    required this.price,
  });
}

class Cart with ChangeNotifier {
  Map<String, CartItem> _items ={} ;
  Map<String, CartItem> get items {
    return  {..._items};
  }
  int get itemCount {
    return _items.length;

  }

  double get totalAmount{
    var total=0.0;
    _items.forEach((key, cartItem) {
      total += cartItem.price*cartItem.quantity;
    });
    

    return total;
  }

  void addItem(String productId, double price, String title) {
    if (_items.containsKey(productId)) {
      _items.update(
          productId,
          (existingCartItem) => CartItem(
              id: existingCartItem.id,
              title: existingCartItem.title,
              quantity: existingCartItem.quantity + 1,
              price: existingCartItem.price));
    } else {
      _items.putIfAbsent(
          productId,
          () => CartItem(
                id: DateTime.now().toString(),
                title: title,
                quantity: 1,
                price: price,
              ));
    }
    notifyListeners();
  }
}

但是如果不使用 values.toString() 它会抛出这个错误

您使用 getter 获取属性:

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    required this.id,
    required this.title,
    required this.quantity,
    required this.price,
  });
  
  String get getId => id;
  String get getTitle => title;
  int get getQuantity => quantity;
  double get getPrice => price;
}

return使用封装总是好的。

Expanded(
  child: ListView.builder(
    itemCount: cart.items.length,
    itemBuilder: (ctx, i) => CartItemDisplay(
      //Use getter
      cart.items.values.[i].getId,
      cart.items.values.[i].getPrice,
      cart.items.values.[i].getQuantity.toString(),
      cart.items.values.[i].getTitle.toString(),
    ),
  ),
),

您可以使用此站点构建模型 classes https://javiercbk.github.io/json_to_dart/ 我认为这个网站对创建你的模型很有用 class 你可以把你的 json 放在这个网站上并得到模型 class

请尝试从购物车价值中获取购物车商品。

final cart = Provider.of<Cart>(context);
final cartItems = cart.items.entries.map((e) => e.value).toList();

...

     Expanded(
        child: ListView.builder(
          itemCount: cartItems.length,
          itemBuilder: (ctx, i) => CartItemDisplay(
          ////* Change these lines.
           cartItems[i].id,
           cartItems[i].price,
           cartItems[i].quantity,
           cartItems[i].title,
            ///////**
          ),
        ),
      ),
...