skip to Main Content
IOWebSocketChannel? ioChannel;
List<CustomRunners>? oldData = [];
List<CustomRunners>? newData = [];
void getSocket(){
    ioChannel = IOWebSocketChannel.connect(
      Uri.parse(
          'wss://xxx.xyz/port=${widget.port}/?logged=true&source=0'),
      headers: {
        'Origin': 'https://abc.io',
      },
    );

    ioChannel?.stream.listen((message) {
      final data = jsonDecode(message);

        if (data[0] != null) {
          final match = SocketModel.fromJson(data[0]);

          newData!.clear();
          for (var item in match.runners!) {
            var obj = CustomRunners(
                marketId: match.marketId,
                runnerName: item.runnerName,
                selectionId: item.selectionId,
                status: item.status,
                exchangePrices: item.exchangePrices,
                lastPriceTraded: item.lastPriceTraded,
                totalMatched: item.totalMatched);

            newData?.add(obj);
          }
          if (newData!.isNotEmpty) {
            oldData!.clear();
            setState(() {
              oldData?.addAll(newData!);
            });
          }
        }
    });
  }
                SizedBox(
                  height: 150,
                  width: MediaQuery.of(context).size.width,
                  child: ListView.builder(
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: newData.length,
                    itemBuilder: (context, index) {
                      var obj = newData[index];
                      var obj2 = oldData[index];

                      if (obj.exchangePrices!.availableToBack!.length == 0 ||
                          obj.exchangePrices!.availableToBack![0].size ==
                              null ||
                          obj2.exchangePrices!.availableToBack![0].size ==
                              null) {
                        back = Color(0xff72bbef);
                      } else {
                        var newAvailSize =
                            obj.exchangePrices!.availableToBack![0].size!;
                        var oldAvailSize =
                            obj2.exchangePrices!.availableToBack![0].size!;

                        if (newAvailSize > oldAvailSize) {
                          back = Color(0xff00FFFF);
                        } else if (newAvailSize < oldAvailSize) {
                          back = Colors.yellowAccent;
                          print(
                              "get  yellowwwwww $newAvailSize and $oldAvailSize");
                        } else if (newAvailSize == oldAvailSize) {
                          back = Color(0xff72bbef);
                        }
                      }
                      }

                      return Row(
                        children: [
                          Expanded(
                            flex: 2,
                            child: AnimatedContainer(
                                duration: Duration(
                                    milliseconds: 50), // animation duration
                                curve: Curves.ease, //
                                height: 50,
                                decoration: BoxDecoration(
                                    color: back,
                                    border: Border(
                                        top: BorderSide(
                                            width: 0.2, color: Colors.black),
                                        bottom: BorderSide(
                                            width: 0.2, color: Colors.black))),
                                child: Text(obj.exchangePrices!.availableToBack![0]
                                        .price
                                        .toString())
                              ),
                          ),
                        ],
                      );
                    },
                  ),
                ),

I have two array oldData and newData. This array getting data from web socket and these data refreshing continuously.I’m trying to change color of container if newData array is greater than oldData array then color will be blue and if newData array is less than oldData array then color will be red else color will be white.I have written the code but unable to get exact output.

This is a code which i have written to change the color of container but color is not changing if i’m clearing the oldData array.In both array getting same data after clearing oldData array.

Can someone help me with this.

4

Answers


  1. To achieve colour changes you have to set value notifier which notifies that value changes & rebuild only that particular widget,

    First declare your back variable like this,

    ValueNotifier<Color> back = ValueNotifier<Color>(Colors.white);
    

    where you update back value write this,

    if (newAvailSize > oldAvailSize) {
    
           back.value = Color(0xff00FFFF);
             back.notifyListeners();
    
    } 
    else if (newAvailSize < oldAvailSize) {
                              
            back.value = Colors.yellowAccent;
            back.notifyListeners();
          print("get  yellowwwwww $newAvailSize and $oldAvailSize");
    
     } else if (newAvailSize == oldAvailSize) {
    
          back.value = Color(0xff72bbef);
            back.notifyListeners();
    }
    

    In your return function set ValueListenableBuilder

    ValueListenableBuilder(
        valueListenable: back,
        builder: (context, backValue, child) {
          return Row(
            children: [
              Expanded(
                flex: 2,
                child: AnimatedContainer(
                    duration: Duration(
                        milliseconds: 50), // animation duration
                    curve: Curves.ease, //
                    height: 50,
                    decoration: BoxDecoration(
                        color: backValue,
                        border: Border(
                            top: BorderSide(
                                width: 0.2, color: Colors.black),
                            bottom: BorderSide(
                                width: 0.2, color: Colors.black))),
                    child: Text(obj.exchangePrices!.availableToBack![0]
                        .price
                        .toString())
                ),
              ),
            ],
          );
        }
    )
    
    Login or Signup to reply.
  2. Both of your arrays newData and oldData will always be the same length because you are clearing oldData and adding newData into it every time it receive a new item, so you will never see changes in color because they’re always the same length.

    Can you try to make a new instance of list instead? so in your getSocket() instead of

    if (newData!.isNotEmpty) {
      oldData!.clear();
      setState(() {
        oldData?.addAll(newData!);
      });
    }
    

    try this:

    if (newData!.isNotEmpty) {
      setState(() {
        oldData = List<CustomRunners>.from(newData!); 
      });
    }
    

    Also maybe move the color comparison out of the listview.builder? because you’re doing a comparison for every item in the list. you might wanna label it outside instead. Heres an example using switch case method:

    Color back(double? newValue, double? oldValue) {
      if (newValue == null || oldValue == null) {
        return Color();
      }
    
      switch (newValue.compareTo(oldValue)) {
        case > 0:
          return Color();
        case < 0:
          return Color();
        case 0:
          return Color();
        default:
          return Color();
      }
    }
    

    so in listview.builder:

    var back = getColor(
            obj.exchangePrices?.availableToBack?.first.size,
            obj2.exchangePrices?.availableToBack?.first.size,
          );
    
    Login or Signup to reply.
  3. It’s like whenever newdata comes last newdata you want to set in old data array so you have to first replace your oldData with current newData then after clear newData & add new records

    set oldData before clearing newData

    if (newData!.isNotEmpty) {
                oldData!.clear();
                setState(() {
                  oldData?.addAll(newData!);
                });
              }
    
    newData!.clear();
    
    …..
    
    Login or Signup to reply.
  4. try this line of code in Container:

    color: (newData.length > oldData.length) ? Colors.blue : (newData.length < oldData.length) ? Colors.red : Colors.white,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search