Search code examples
flutterlistdartsplitsublist

How to return a list of sublists from a specific item with flutter?


Actually, I'm trying to return a list from the 19th index, but this didn't work for me. This list is split into sub lists. I want to start splitting it from the 19th index not from 0.

This is my code:

static Future<List> local() async {
    File textAsset = File('/storage/emulated/0/RPSApp/assets/bluetooth.txt');
    final text = await textAsset.readAsString();
    final bytes =
        text.split(',').map((s) => s.trim()).map((s) => int.parse(s)).toList();

    int chunkSize = 19;


    List<int> padTo(List<int> input, int count) {
      return [...input, ...List.filled(count - input.length, 255)];
    }

    List<int> padToChunksize(List<int> input) => padTo(input, chunkSize);
    List<List<int>> items;
    items = bytes.slices(chunkSize).map(padToChunksize).toList();
    for (int i = 19; i < bytes.length; i++) {
      return items;
    }

    return items;
  }

this code is for displaying sublists one by one:

 final chun = await Utils.local();
 await Future.forEach(chun, (ch) async {

                  

                    await Future.delayed(const Duration(seconds: 4));
                    await c.write(chun, withoutResponse: true);
                    await c.read();
                    await Future.wait(getValue());
                  }
                })

I don't know what's wrong with this code and why it returns me the list from index 0.


Solution

  • Honestly its quite difficult to understand your code. since its mixed in 1 function.

    its return from index 0 because:

     items = bytes.slices(chunkSize).map(padToChunksize).toList();
    

    and then you keep return items. which is return all items. you have to create new list and cut the index based on you need.


    Solutions:

    ill answer based on list that you provide in comment section:

    List data = [144, 9, 146, 8, 191, 0, 32, 0, 240, 84, 130, 16, 70, 79, 240, 0, 11, 170, 0, 0, 0, 242];
    
    // method 1 ( recomended) 
    final newList = data.skip(19);
    print(newList); // result: (0, 0, 242)
    
    // method 2
    final newlist2 = temp.getRange(19,data.length);
    print(newlist2); // result: (0, 0, 242)
    
    

    both method will return the list from index 19. choode which method do you like to use. i will recommend to use skip, since it will not throw error if the list length is less than 19