Search code examples
flutterlistdartsplitsublist

How to split a list into sublists using flutter?


I'm new with flutter. I have data in txt file I retrieve it, then, I convert it into list and finally I split this list into sublists. Every sublist contains 19 values. It's okey for this part. But now, the problem is that in the end of file we could have less than 19 values. So my question is how to add this values to another sublist also. Actually, those sublists contains hexadecimals values, I was thinking about filling the last sublist with zeros until we have 19 values.But, I don't know how to do this. Or, if you have any other solution to fix this issue? this is my code:

  static Future<List> localPath() 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();

    final chunks = [];
    //final list4 = [];
    int chunkSize = 19;

    for (int i = 0; i < 40; i += chunkSize) {
      chunks.add(bytes.sublist(
          i, i + chunkSize > bytes.length ? bytes.length : i + chunkSize));
    }

    return chunks;
  }

Thanks in advance for your help


Solution

  • import 'package:collection/collection.dart'; // add to your pubspec
    final newList = originalList.slices(19).toList();
    

    Done. Read the documentation for details.

    Edit: After reading your comment, I came up with this:

    import 'dart:math';
    
    import 'package:collection/collection.dart';
    
    void main(List<String> arguments) {
      final random = Random();
      const chunkSize = 7;
      final source = List.generate(100, (index) => random.nextInt(100) + 1);
    
      List<int> padTo(List<int> input, int count) {
        return [...input, ...List.filled(count - input.length, 0)];
      }
    
      List<int> padToChunksize(List<int> input) => padTo(input, chunkSize);
    
      final items = source.slices(chunkSize).map(padToChunksize).toList();
      print(items);
    }
    

    which demonstrates how to pad each short list with more 0's.