What is the proper way to do a foreach loop with an Array/Map in dart?

104
May 12, 2022, at 6:10 PM

I'm trying to convert a piece of PHP code to dart and getting stuck. What I have is a PHP array text that gets run through a function called toUTF8 as follows:

if(is_array($text))
{
  foreach($text as $k => $v)
    {
    text[$k] = self::toUTF8($v);
    }
  return $text;
}

Conceptually, what I've done in dart is turn text into a Map

if(text is Map)
{
  foreach(text as k => v)
    {
    text[k] = toUTF8(v);
    }
  return text;
}

But I cannot wrap my mind around, how I would walk the map and run each element into the toUTF8 function.

Essentially, the question is how to do a foreach on a map?

For bonus points, would treating it as a List is a better approach? What this code is ultimately doing is handling malformed UTF8 characters

Answer 1

I'd probably keep it as an array. I don't see any good reason for using a map.

What are the contents of the text array? Is it strings or UTF-8 bytes? Is it individual string characters, or longer strings? Since you call something called toUTF8, I'm assuming it's strings, and you want to convert them to UTF-8. I'm not sure how the code "handles" malformed UTF-8 sequences, since it appears to convert to UTF-8.

You are doing that on a chunk-by-chunk basis, but that's not necessarily correct, if the text array represents a single large text chopped into pieces. Dart strings are sequences of UTF-16 code units, and a surrogate pair can be split between separate chunks, but must be converted together.

I'd do something like:

var bytes = Stream.fromIterable(text).transform(utf8.encoder);
// do something with `bytes`.

or, if you want manual control:

import "dart:convert";
import "dart:typed_data";
// ...
  var buffer = BytesBuilder();
  var converter = utf8.encoder.startChunkedEncoding(
      ByteConversionSink.withCallback(buffer.add));
  text.forEach(converter.add);
  converter.close();
  var bytes = buffer.takeBytes(); // UTF-8 converted `text`.
Rent Charter Buses Company
READ ALSO
Laravel Error: Details blade displays wrong data, displays previous column data

Laravel Error: Details blade displays wrong data, displays previous column data

I have a Details page that displays "short description", "Duration", and "description of tour" from a database

64
File Download via API using Guzzle

File Download via API using Guzzle

I'm still on the learning slopes with Guzzle, but am stumped with this issue

84
How would i curl a hls using php

How would i curl a hls using php

I want to curl a HLS that returns forbidden in the browser with Php so in another words i want to return the contents of say

143
Complex query between 4 tables in Laravel

Complex query between 4 tables in Laravel

I have 4 tables : users , user_store_info , user_store_options , product_supplies

106