import ‘package:flutter/material.dart’;
import ‘ShoppingListItem.dart’;

class ShoppingList extends StatefulWidget {
ShoppingList({Key key, this.products}) : super(key: key);

final List products;

// The framework calls createState the first time a widget appears at a given
// location in the tree. If the parent rebuilds and uses the same type of
// widget (with the same key), the framework re-uses the State object
// instead of creating a new State object.

_ShoppingListState createState() => _ShoppingListState();

class _ShoppingListState extends State {
Set _shoppingCart = Set();

void _handleCartChanged(Product product, bool inCart) {
setState(() {
// When a user changes what’s in the cart, we need to change _shoppingCart
// inside a setState call to trigger a rebuild. The framework then calls
// build, below, which updates the visual appearance of the app.

  if (inCart)


Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Shopping List’),
body: ListView(
padding: EdgeInsets.symmetric(vertical: 8.0),
children: widget.products.map((Product product) {
return ShoppingListItem(
product: product,
inCart: _shoppingCart.contains(product),
onCartChanged: _handleCartChanged,

void main() {
title: ‘Shopping App’,
home: ShoppingList(
products: [
Product(name: ‘Eggs’),
Product(name: ‘Flour’),
Product(name: ‘Chocolate chips’),


### 第二个

import ‘package:flutter/material.dart’;

class Product {
const Product({this.name});

final String name;

typedef void CartChangedCallback(Product product, bool inCart);

class ShoppingListItem extends StatelessWidget {
ShoppingListItem({Product product ,this.inCart , this.onCartChanged})
: product = product,
super(key: ObjectKey(product));

final Product product;
final bool inCart ;
final CartChangedCallback onCartChanged;

Color _getColor(BuildContext context) {
return inCart ? Colors.black54 : Theme.of(context).primaryColor;

TextStyle _getTextStyle(BuildContext context) {
if (!inCart) return null;

return TextStyle(
    color: Colors.black54, decoration: TextDecoration.lineThrough);


Widget build(BuildContext context) {
return ListTile(
onTap: () {
onCartChanged(product, !inCart);
leading: CircleAvatar(
backgroundColor: _getColor(context),
child: Text(product.name[0]),
title: Text(
style: _getTextStyle(context),