skip to Main Content

When I press the button it count in all of the cards, I want it to count in each on of them separately

making an app in flutter,
When I press the go button counter works in all of the cards, I want it to count in each on of them separately,
I hope somebody help me.

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:ziker/text_format.dart';

class TestPage extends StatefulWidget {
  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  // Create a list of texts
  final List<String> texts = [
   "Hello world",
"Hello world!2"

  ];

  final List<int> subTexts = [
    1,
    2,
  
  ];

  int counter = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text(
          "أذكار الصباح",
          textDirection: TextDirection.rtl,
          style: GoogleFonts.arefRuqaa(
            fontSize: 24,
            fontWeight: FontWeight.w700,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
      ),
      body: Container(
        padding: EdgeInsets.all(
          25,
        ),
        child: ListView.builder(
          // Set the length of the list
          itemCount: texts.length,
          // Return a Card widget for each item
          itemBuilder: (context, index) {
            return Padding(
              padding: const EdgeInsets.symmetric(
                vertical: 8,
              ),
              child: Card(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                  //set border radius more than 50% of height and width to make circle
                ),
                // Use a Column to arrange the text and the buttons vertically
                child: Container(
                  padding: const EdgeInsets.all(25.0),
                  color: Colors.amber,
                  child: Column(
                    children: [
                      // Display the text inside the card
                      AmiriText(
                        text: texts[index],
                        fontS: 25,
                        textDirection: TextDirection.rtl,
                      ),
                      SizedBox(
                        height: 25,
                      ),
                      CircleAvatar(
                        child: Text(
                          subTexts[index].toString(),
                        ),
                      ),
                      SizedBox(
                        height: 25,
                      ),
                      // Use a Row to display the two buttons horizontally
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Color(0xFF086788),
                              foregroundColor: Color(0xFF9CAFB7),
                              shadowColor: Colors.grey[400],
                              elevation: 3,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(
                                  10.0,
                                ),
                              ),
                              minimumSize: Size(100, 40),
                            ),
                            child: AmiriText(
                              text: "return back",
                              fontS: 18,
                              color: Colors.white,
                            ),
                            onPressed: () {
                              setState(() {
                                if (counter > 0) {
                                  counter--;
                                }
                              });
                            },
                          ),
                          Text(
                            counter.toString(),
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                          ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Color(0xFF062726),
                              foregroundColor: Color(0xFF66A182),
                              shadowColor: Colors.grey[400],
                              elevation: 3,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(
                                  10.0,
                                ),
                              ),
                              minimumSize: Size(100, 40),
                            ),
                            child: AmiriText(
                              text: "Go",
                              fontS: 18,
                              color: Colors.white,
                            ),
                            onPressed: () {
                              setState(() {
                                counter++;
                              });
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

initialize in each one of them separately not all of them

2

Answers


  1. Yes it is happening because you have made a single counter variable for all list view items. i.e.

    int counter = 0;
    

    What you need to do is create a separate variable for each listview item.

    One approach could be using a List of int instead of a single int variable.

    List<int> counters = [];
    

    The builder will add a new variable for each iteration.

    counters.add(0);
    

    You can will access it using the index of ListView.builder.

    counters[index]++;
    

    For your ease I have used your code example to show it. You can test it using below code.

    import 'package:flutter/material.dart';
    
    class TestPage extends StatefulWidget {
      const TestPage({super.key});
    
      @override
      State<TestPage> createState() => _TestPageState();
    }
    
    class _TestPageState extends State<TestPage> {
      // Create a list of texts
      final List<String> texts = [
        "Hello world",
        "Hello world!2"
    
      ];
    
      final List<int> subTexts = [
        1,
        2,
      ];
    
      // int counter = 0;
      List<int> counters = [];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.grey[200],
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            title: const Text(
              "أذكار الصباح",
              textDirection: TextDirection.rtl,
            ),
            centerTitle: true,
          ),
          body: Container(
            padding: const EdgeInsets.all(
              25,
            ),
            child: ListView.builder(
              // Set the length of the list
              itemCount: texts.length,
              // Return a Card widget for each item
              itemBuilder: (context, index) {
                counters.add(0);
                return Padding(
                  padding: const EdgeInsets.symmetric(
                    vertical: 8,
                  ),
                  child: Card(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                      //set border radius more than 50% of height and width to make circle
                    ),
                    // Use a Column to arrange the text and the buttons vertically
                    child: Container(
                      padding: const EdgeInsets.all(25.0),
                      color: Colors.amber,
                      child: Column(
                        children: [
                          // Display the text inside the card
                          AmiriText(
                            text: texts[index],
                            fontS: 25,
                            textDirection: TextDirection.rtl,
                          ),
                          SizedBox(
                            height: 25,
                          ),
                          CircleAvatar(
                            child: Text(
                              subTexts[index].toString(),
                            ),
                          ),
                          SizedBox(
                            height: 25,
                          ),
                          // Use a Row to display the two buttons horizontally
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: <Widget>[
                              ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Color(0xFF086788),
                                  foregroundColor: Color(0xFF9CAFB7),
                                  shadowColor: Colors.grey[400],
                                  elevation: 3,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(
                                      10.0,
                                    ),
                                  ),
                                  minimumSize: Size(100, 40),
                                ),
                                child: AmiriText(
                                  text: "return back",
                                  fontS: 18,
                                  color: Colors.white,
                                ),
                                onPressed: () {
                                  setState(() {
                                    if (counters[index] > 0) {
                                      counters[index]--;
                                    }
                                  });
                                },
                              ),
                              Text(
                                counters[index].toString(),
                                style: const TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.w700,
                                ),
                              ),
                              ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Color(0xFF062726),
                                  foregroundColor: Color(0xFF66A182),
                                  shadowColor: Colors.grey[400],
                                  elevation: 3,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(
                                      10.0,
                                    ),
                                  ),
                                  minimumSize: Size(100, 40),
                                ),
                                child: AmiriText(
                                  text: "Go",
                                  fontS: 18,
                                  color: Colors.white,
                                ),
                                onPressed: () {
                                  setState(() {
                                    counters[index]++;
                                  });
                                },
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        );
      }
    
      AmiriText({required String text, required int fontS, Color? color, TextDirection? textDirection}) {
        return Text(text);
      }
    }
    
    Login or Signup to reply.
  2. Consider using a List of Maps so you can label each parameter:

    final List<Map<String, dynamic>> texts = [
        {'title': 'Hello World',
          'number' : 1,
        'counter': 0},
        {'title': 'Hello World!2',
          'number': 2,
        'counter': 0},
      ];
    

    You can now increase the counter parameter for each item in a list individually like this:

    setState(() {
      if (texts[index]['counter'] > 0) {
        texts[index]['counter']--;
      }
    });
    

    See full demo here:

    https://dartpad.dev/?id=093c9cf9ecd8f87a09c76c763e78c9e5

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search