Flutter Cart

1. Button Details

Expanded(
    child: Row(
        children: [
            ElevatedButton.icon(
                onPressed: () => Navigator.pushNamed(context, '/details', arguments: bike.id),
                label: Text('Details'),
                icon: Icon(Icons.details),
            ),
        ],
    ),
)

2. Detail Page

class _DetailsPageState extends State<DetailsPage> {
  Bike? _bike;
  List<Bike> _relation = [];
  int? _id;
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _id ??= ModalRoute.of(context)!.settings.arguments as int;
    _loadBike();
  }
  void _loadBike() async {
    var item = await BikeRepository.getBike(_id!);
    var data = await BikeRepository.getBikesRelation(
      item.id,
      item.subCategoryId,
    );
    setState(() {
      _bike = item;
      _relation = data;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget._title),
        actions: [
          ElevatedButton.icon(
            onPressed: () {
              Navigator.pushNamedAndRemoveUntil(context,'/cart', ModalRoute.withName('/'));
            },
            label: Text('Cart'),
            icon: Icon(Icons.shopping_bag),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            if (_bike != null) _showDetails(_bike!),
            if (_relation.isNotEmpty)
              GridView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: _relation.length,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
                itemBuilder: (context, index) {
                  Bike bike = _relation[index];
                  return Column(
                    children: [
                      Image.network("${dotenv.env['API_URL']}/bikes/${bike.imageUrl}", width: 256),
                      Text(bike.name),
                      Text('Price: ${bike.price}'),
                    ],
                  );
                },
              ),
          ],
        ),
      ),
    );
  }
}

3. Show Details

Widget _showDetails(Bike item) {
    return Column(
      children: [
        Image.network('${dotenv.env['API_URL']}/bikes/${item.imageUrl}',width: 512),
        Table(
          columnWidths: {0: FlexColumnWidth(1), 1: FlexColumnWidth(3)},
          children: [
            TableRow(children: [Text('Price'), Text(item.price.toString())]),
            if (item.brakes != null)
              TableRow(children: [Text('Brakes'), Text(item.brakes!)]),
            if (item.fork != null)
              TableRow(children: [Text('Fork'), Text(item.fork!)]),
            if (item.wheels != null)
              TableRow(children: [Text('Wheels'), Text(item.wheels!)]),
            if (item.drivetrain != null)
              TableRow(children: [Text('Drivetrain'), Text(item.drivetrain!)]),
            if (item.frame != null)
              TableRow(children: [Text('Frame'), Text(item.frame!)]),
            if (item.tires != null)
              TableRow(children: [Text('Tires'), Text(item.tires!)]),
          ],
        ),
        ElevatedButton.icon(onPressed: _addToCart, label: Text('Add to Cart')),
      ],
    );
}

4. Add to Cart

void _addToCart() async {
    String? token = await SessionHelper.token;
    if (token != null) {
      try {
        int ret = await CartRepository.add(
          Cart(memberId: null, bikeId: _id!, quantity: 1, bikeName: null, imageUrl: null, price: null),
          token,
        );
        if (!mounted) return;
        if (ret > 0) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Add to Cart Success')));
        } else {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Add to Cart Failed $ret')));
        }
      } catch (ex) {
        debugPrint(ex.toString());
      }
    } else {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Please login')));
    }
}

5. Cart Page

class _CartPageState extends State<CartPage> {
  List<Cart> _carts = [];
  static final String? _url = dotenv.env['API_URL'];
  @override
  void initState() {
    super.initState();
    _loadData();
  }
  void _loadData() async {
    String? token = await SessionHelper.token;
    if (token != null) {
      var carts = await CartRepository.getCarts(token);
      setState(() {
        _carts = carts;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget._title)),
      body: DataTable(
        columns: [
          DataColumn(label: Text('Name')),
          DataColumn(label: Text('Image')),
          DataColumn(label: Text('Price')),
          DataColumn(label: Text('Quantity'), columnWidth: IntrinsicColumnWidth()),
          DataColumn(label: Text('Command'), columnWidth: IntrinsicColumnWidth()),
        ],
        rows: _carts.map((p) {
          return DataRow(
            cells: [
              DataCell(Text(p.bikeName!)),
              DataCell(Image.network('$_url/bikes/${p.imageUrl}', width: 64)),
              DataCell(Text(p.price.toString())),
              DataCell(Text(p.quantity.toString())),
              DataCell(
                ElevatedButton.icon(onPressed: () => _delete(p), label: Text('Delete'), icon: Icon(Icons.delete)),
              ),
            ],
          );
        }).toList(),
      ),
    );
  }
  void _delete(Cart item) async {
    String? token = await SessionHelper.token;
    if (token != null) {
      int ret = await CartRepository.delete(item.bikeId, token);
      if (ret > 0) {
        _loadData();
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Delete Success')));
      }
    }
  }
}