Search code examples
flutterdartnetwork-programmingtcp

How to convert objects to byte arrays in dart


I need to convert some data into a custom defined packet format in flutter. To do this, I want to convert the individual data into a byte array which can be passed down the TCP socket.

I have converted the needed into an object but cannot find a solution to serialize it


Solution

  • One of the possible solutions might be converting your object into a JSON string and converting that string to bytes using dart:convert

    // example object
    final Example example =
        Example(name: "name", age: "age", address: "address");
    
    // convert into bytes
    
    // encode the object to a JSON string
    String jsonString = jsonEncode(example);
    
    // encode the string to a UTF-8 byte array
    List<int> bytes = utf8.encode(jsonString);
    
    // print the bytes for testing
    print(bytes);
    

    and don't forget to import

    import 'dart:convert';