0

I have a Flutter app which uses ObjectBox to store back-end data, which is a list of Product objects. I have created a ListView Tile widget to present the data called ProductTile. I generate a ListView widget with the following code:

class productTileListView extends StatefulWidget {
  const productTileListView({Key? key}) : super(key: key);

  @override
  State<productTileListView> createState() => _productTileListViewState();
}

class _productTileListViewState extends State<productTileListView> {

  ProductTile Function(BuildContext, int) _itemBuilder(List<Product> products) {
    return (BuildContext context, int index) => ProductTile(product: products[index], setStateCallback: () => { setState(() {}) });
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<Product>>(
      stream: objectbox.getProducts(),
      builder: (context, snapshot) {
        if (snapshot.data?.isNotEmpty ?? false) {
          return ListView.builder(
              itemCount: snapshot.hasData ? snapshot.data!.length : 0,
              itemBuilder: _itemBuilder(snapshot.data ?? []));
        } else {
          return const Center(child: Text("No products"));
        }
      },
    );
  }
}

This code works perfectly, and gives me a ListView of ProductTiles which visualizes the data in each Product object. However, I am at a loss for how to loop through the ProductTiles to perform actions on them. For example, they track whether they are currently selected with a bool, and I would like to be able to implement something like this: productTiles.removeWhere((item) => item.isSelected); I can't perform this on the base Product object because isSelected is only part of ProductTiles.

One solution I have thought of is to instead change my ObjectBox database to instead store ProductTiles, however this seems sub-optimal as I would be storing a bunch of UI related parameters such as whether the tile is selected etc instead of storing just the necessary information.

This seems like it would be a pretty common part of app development, so please let me know what the best practice is to address this.

1 Answer 1

1

You can use a list or map for storing selected products and pass it to your remove method.

  • List elements can be either productId or index
  • you can also use a map with
    • Key : productId or index
    • Value: bool (default set to false)

Similar/Related question: Select and deselect List Tile

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.