Search code examples
flutterdartlistview

How to overwrite a global variable's value by declaring it inside a listview


This is for a stopwatch functionality. The xCountUpDuration is the default time for the stopwatch and I have set it in 2 places, one is outside listview (Code 1) and the value is set to 0 and the other is inside listview (Code 3) and the value is set to 10 minutes. The problem is when I call the (Code 2) widget inside listview of (Code 3), the value is set to 0 instead of 10 minutes. How can I make it use the xCountUpDuration value set in Code 3.

Code 1

  Duration xCountUpDuration = Duration();

  Timer? xCountUpTime;

  void xCountUpActionStart() {

    xCountUpActionEnd();

    xCountUpTime = Timer.periodic(Duration(seconds: 1), (_) => xCountUpActionAddTime());
  }

  void xCountUpActionEnd() {

    setState(() => xCountUpTime?.cancel());

  }

  void xCountUpActionAddTime() {

    final xAddSeconds = 1;

    setState(() {

      final seconds = xCountUpDuration.inSeconds + xAddSeconds;

      xCountUpDuration = Duration(seconds: seconds);

    });

  }

Code 2

  Widget xCountUpTimerWidget() {

    String xDigitConverter(int n) => n.toString().padLeft(2, '0');

    final xHours = xDigitConverter(xCountUpDuration.inHours);

    final xMinutes = xDigitConverter(xCountUpDuration.inMinutes.remainder(60));

    final xSeconds = xDigitConverter(xCountUpDuration.inSeconds.remainder(60));

    return Text(

      '$xHours:$xMinutes:$xSeconds',

      style: TextStyle(

        fontSize: 60,

        fontWeight: FontWeight.w700,

      ),

    );

  }

Code 3

return ListView.builder(

  itemBuilder: (context, index) {

    Duration xCountUpDuration = Duration(hours: 00, minutes: 10, seconds: 00);

    return Column(

      children: [

        xCountUpTimerWidget(),

      ]

    )

  }

Solution

  • Let your Widget know about the value of the variable:

    return ListView.builder(
    
          itemBuilder: (context, index) {
    
          Duration xInnerCountUpDuration = Duration(hours: 00, minutes: 10, seconds: 00);
    
          return Column(
    
            children: [
    
              xCountUpTimerWidget(xInnerCountUpDuration ),
    
            ]
          )}
    

    Code 2:

    Widget xCountUpTimerWidget(Duration param) {
    
        String xDigitConverter(int n) => n.toString().padLeft(2, '0');
    
        final xHours = xDigitConverter(param.inHours);
    
        final xMinutes = xDigitConverter(param.inMinutes.remainder(60));
    
        final xSeconds = xDigitConverter(param.inSeconds.remainder(60));
    
        return Text(
    
          '$xHours:$xMinutes:$xSeconds',
    
          style: TextStyle(
    
            fontSize: 60,
    
            fontWeight: FontWeight.w700,
    
          ),
    
        );