import 'package:flutter/material.dart';
import 'ShoppingListItem.dart';
class ShoppingList extends StatefulWidget {
ShoppingList({Key key, this.products}) : super(key: key);
List<Product> products;
@override
State<StatefulWidget> createState() => new _ShoppingListState();
}
class _ShoppingListState extends State<ShoppingList> {
Set<Product> _shoppingCart = new Set<Product>();
void _handleCartChanged(Product product, bool inCart) {
setState(() {
if (inCart)
_shoppingCart.add(product);
else
_shoppingCart.remove(product);
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('购物应用'),
),
body: new ListView(
children: widget.products.map((Product product) {
return new ShoppingListItem(
product: product,
inCart: _shoppingCart.contains(product),
onCardChanged: _handleCartChanged,
);
}).toList(),
),
);
}
}
final List<Product> _Products = <Product>[
new Product(name: 'tangbo'),
new Product(name: 'burenshi'),
new Product(name: '你好呀'),
];
void main() {
runApp(
new MaterialApp(
title: 'Flutter教程',//第一次构建,需要传一个商品的list
home: new ShoppingList(products: _Products),
),
);
}
复制代码
import 'package:flutter/material.dart';
class Product {
final String name;
const Product({this.name});
}
typedef void CardChangedCallBack(Product product, bool inCart); //类型定义方法 购物车改变回调
/**
* 购物车listitem
*/
class ShoppingListItem extends StatelessWidget {
//构造方法 传入产品
ShoppingListItem({Product product, this.inCart, this.onCardChanged})
: product = product,
super(key: new ObjectKey(product));
final Product product;
final bool inCart;
final CardChangedCallBack onCardChanged;
/**
* 是否在购物车中 ,如果是的话,灰色 ,不是显示主题的主要颜色
*/
Color _getColor(BuildContext context) {
return inCart ? Colors.black54 : Theme.of(context).primaryColor;
}
/**
* 是否在购物车中 ,如果在购物车中,显示划掉文字style
*/
TextStyle _getTextStyle(BuildContext context) {
if (!inCart) return null;
return new TextStyle(
color: Colors.black54, decoration: TextDecoration.lineThrough);
}
@override
Widget build(BuildContext context) {
return new ListTile(
onTap: () {
onCardChanged(product, !inCart);
},
leading: new CircleAvatar(
backgroundColor: _getColor(context),
child: new Text(product.name[0]), //显示首字母
),
title: new Text(
product.name,
style: _getTextStyle(context),
),
);
}
}
复制代码
@override
Widget build(BuildContext context) {
return new ListTile(
onTap: () {
onCardChanged(product, !inCart);
},
leading: new CircleAvatar(
backgroundColor: _getColor(context),
child: new Icon(
Icons.ac_unit,
), //显示首字母
),
trailing: new Icon(
Icons.add,
color: _getColor(context),
),
subtitle:new Container(
color: Colors.red,
child: new Text(product.name[0]),
),
// enabled: !inCart,
isThreeLine: true,
title: new Text(
product.name,
style: _getTextStyle(context),
),
);
}
}
复制代码
LIstTile 控件