Reputation: 71
I have a list of strings pulled from database as a string
[name 1, name2, name3, ...]
i am trying to convert it to this:
'name 1', 'name2', 'name3', '...'
so far no success. method with which i am getting data. The method is just fine since I am using it beforehand for other part of code.
Future<List<String>> getNames() async {
var url = _api + "get_names.php?key=" + _key;
http.Response response = await http.get(url);
var resp = jsonDecode(response.body);
return resp.map<String>((m) => m['names'] as String).toList();
}
list is pulled from database as a String.
Basicaly I am using a part of formbuilder code which uses initialValue as dynamic. so if I set initialValue: [widget.names] and the widget.names contains 'name1','name2' it is ok if it is a list of string but It needs to be ofcourse single or double quoted and seperated with comma.
Thank you
Upvotes: 2
Views: 6662
Reputation: 77374
void main() {
final input = '[name 1, name2, name3, ...]';
final removedBrackets = input.substring(1, input.length - 1);
final parts = removedBrackets.split(', ');
var joined = parts.map((part) => "'$part'").join(', ');
print(joined);
}
Using: https://api.flutter.dev/flutter/dart-core/String/split.html
Prints:
'name 1', 'name2', 'name3', '...'
That said... maybe you should find a better way to get your data. Maybe as Json or something, so you don't have to reinvent serialization. What happens for example if "name 1" has a comma in it? Or let's say it's d'Artagnan?
Upvotes: 8