shrikantha nayak
shrikantha nayak

Reputation: 91

Dart: How to Calculate two values in ListviewBuilder using TextFromFields?

How to Calculate values inlistviewbuilder?

FlutterListviewBuilder

> like 15+23=38

etc...

Using this list in List View builder How to calculate Values?

var product = [
    {"id": 1, "items": "Item 1", "qty": 15},
    {"id": 2, "items": "Item 2", "qty": 20},
    {"id": 3, "items": "Item 3", "qty": 50},
    {"id": 4, "items": "Item 4", "qty": 12},
    {"id": 5, "items": "Item 5", "qty": 35},
    {"id": 6, "items": "Item 6", "qty": 26},
    {"id": 7, "items": "Item 7", "qty": 12},
    {"id": 8, "items": "Item 8", "qty": 25},
    {"id": 9, "items": "Item 9", "qty": 22},
    {"id": 10, "items": "Item 10", "qty": 28},
    {"id": 11, "items": "Item 11", "qty": 24},
    {"id": 12, "items": "Item 12", "qty": 16}
  ];

how to calculate in Listviewbuilder??

Upvotes: 1

Views: 389

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63864

We need List<TextEditingController> with listen for updating value.

You can follow this widget and decorate the way you like

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

  @override
  State<ListVCalculator> createState() => _ListVCalculatorState();
}

class _ListVCalculatorState extends State<ListVCalculator> {
  final int itemsLength = 12;

  List<TextEditingController> controllers = [];
  List<int> firstNumbers = [];

  @override
  void initState() {
    super.initState();

    controllers = List.generate(itemsLength, (index) {
      firstNumbers.add(index + 1 * index + 20); // use random number

      return TextEditingController()
        ..addListener(() {
          setState(() {});
        });
    });
  }

  String _result(int index) {
    final int num =
        int.tryParse(controllers[index].text.trim().toString()) ?? 0;

    return "${num + firstNumbers[index]}";
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: itemsLength,
        itemBuilder: (context, index) {
          return ListTile(
            leading: Text("Item $index"),
            title: Row(
              children: [
                Text("${firstNumbers[index]}"),
                const SizedBox(
                  width: 100,
                ),
                SizedBox(
                  width: 100,
                  child: TextField(
                    controller: controllers[index],
                  ),
                )
              ],
            ),
            trailing: Text(_result(index)),
          );
        },
      ),
    );
  }
}

Upvotes: 1

Related Questions