How can I convert a List<String> to String []? - flutter

I have this String
List<String> params = ['A','B','C'];
I want to convert this to "['A']['B']['C']"
How can I convert this properly?

You can try:
void main(){
List<String> params = ['A','B','C'];
final out = params.map((e) => "['$e']").join();
print(out);
}
Prints:
['A']['B']['C']

you can do this
List<String> params = ['A','B','C'];
List newParams = [];
for(var item in params){
newParams.add([item]);
}
String stringParams = newParams.toString();
String noBracketParams = stringParams.substring( 1, stringParams.length - 1 );
String noCommasParams = noBracketParams.replaceAll(',', '');
print(noCommasParams);

I'm not sure what you're trying to do, but it can be achieved like this
List<String> params = ['A', 'B', 'C'];
List.generate(
params.length, (index) => params[index] = '''['${params[index]}']''');
var str = '';
params.forEach((item) => str += item);
print(str);

Related

How to extract specific string from whole string?

I have following strings :
String? hello = "(1.2,1.5 | 5)"
String? hi = "(2.3,3.2 | 9)"
Now I want to get
var newhello1 = 1.2,1.5
var newhello2 = 5
and
var newhi1 = 2.3,3.2
var newhi2 = 9
How to extract those text from that entire strings?
You can use the indexOf function combined with the substring to get the substrings as follows
var newhello1 = hello.substring(hello.indexOf('(') + 1, hello.indexOf('|')).trim(); //Use Trim() to get rid of any extra spaces
var newhello2 = hello.substring(hello.indexOf('|') + 1,hello.indexOf(')')).trim();
print(newhello1); //1.2,1.5
print(newhello2); //5
List<String> myformatter(String? data) {
if (data == null) return [];
List<String> ls = data.split("|");
for (int i = 0; i < ls.length; i++) {
ls[i] = ls[i].replaceAll("(", "").replaceAll(")", "").trim();
}
return ls;
}
main() {
String? hello = "(1.2,1.5 | 5)";
String? hi = "(2.3,3.2 | 9)";
final helloX = myformatter(hello);
print(helloX[0]); //1.2,1.5
print(helloX[1]); //5
final hiX = myformatter(hi);
print(hiX[0]); //2.3,3.2
print(hiX[1]); //9
}

How to call a List with Strings to make the call dynamic

I'm searching for create a dynamic form which contain DropDownButtons.
Before do that, I'm trying something on DartPad to know if it's possible to call a list with some Strings.
Below an example about what I want to do (maybe what I'm searching for is now possible) :
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},
{"name": "5A"}
];
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(listOfType);
}
In this case it print "listOf3AInitial" and I want to print the List {"name": "4A"},{"name": "5A"}.
How it is possible to do that ?
Regards
You have to map a string of it's value to do so. For example
List<Map<String, String>> listOf3AInitial = [{"name": "4A"}, {"name": "5A"}];
Map<String, List<Map<String, String>>> list3AInitialMap = {
"listOf3AInitial" : listOf3AInitial,
};
Now you can get a value from this map like
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(list3AInitialMap[listOfType]);
Your var listOfType returns a String. Unfortunately, you cannot use/convert String as a variable name.
In this case, you may want to use a map:
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},{"name": "5A"}];
List<Map<String, String>> listOf3BInitial = [{"name": "4B"},{"name": "5B"}];
String _listOf = "listOf";
String _yearA = "3A"; //A
String _yearB = "3B"; //B
String _type = "Initial";
//Reference your lists in a map
Map<String, dynamic> myLists = {
"listOf3AInitial": listOf3AInitial,
"listOf3BInitial": listOf3BInitial
};
//This returns your listOf3AInitial
var listOfType = myLists["$_listOf$_yearA$_type"];
print(listOfType);
//You may also access it directly
print(myLists["$_listOf$_yearB$_type"]);
}

How to split a string in Flutter while also including delimiters

+37.4054-122.0999/
The above coordinates are my output. I want to split the string in such a way that it shows +37.4054 and -122.0999 as substrings which includes the + and - signs.
You can do
string.split(RegExp('(?=[+-])'));
Example:
var string = '+37.4054-122.0999';
var string2 = '-37.4054+122.0999';
var string3 = '+37.4054+122.0999';
var string4 = '-37.4054-122.0999';
var a = string.split(RegExp('(?=[+-])'));
var b = string2.split(RegExp('(?=[+-])'));
var c = string3.split(RegExp('(?=[+-])'));
var d = string4.split(RegExp('(?=[+-])'));
print(a);
print(b);
print(c);
print(d);
Output:
[+37.4054, -122.0999]
[-37.4054, +122.0999]
[+37.4054, +122.0999]
[-37.4054, -122.0999]
Try use split method:
const string = '+37.4054-122.0999';
final splitted = string.split('-');
print(splitted); //['+37.4054', '122.0999'];
print(splitted[0]); //+37.4054;
print('-' + splitted[1]); //-122.0999;
Try this:
void main() {
final String coord = '+37.4054-122.0999';
final int plusIndex = coord.indexOf('+');
final int minusIndex = coord.indexOf('-');
final plus = coord.substring(plusIndex, minusIndex);
final minus = coord.substring(minusIndex, );
print('plus: $plus, minus: $minus');
}

Dart - convert Webfeed to Json

I am new to dart and flutter. I am learning and trying to make an app that reads Atomic feed from the website. I am using webfeed package to accomplish this.
Here is the code I have so far -
Future<NewsModel> fetchLatestNews() async {
final response = await client.get("https://www.example.com/blog-news-list/atom/");
if(response.statusCode == 200){
var atomFeed = new AtomFeed.parse(response.body);
Map map = new Map();
for (int i = 0; i < atomFeed.items.length; i++) {
map[i]["title"] = atomFeed.items[i].title;
map[i]["link"] = atomFeed.items[i].id;
map[i]["published"] = atomFeed.items[i].published;
map[i]["summary"] = Helpers.removeAllHtmlTags(atomFeed.items[i].summary);
}
return NewsModel.fromJson(json.decode(map.toString()));
}else {
throw Exception("Failed to load post.");
}
}
And here is my news_model.dart
class NewsModel{
List<_Result> _results = [];
NewsModel.fromJson(Map<String, dynamic> parsedJson) {
List<_Result> temp = [];
for (int i = 0; i < parsedJson.length; i++) {
_Result result = _Result(parsedJson[i]);
temp.add(result);
}
_results = temp;
}
List<_Result> get results => _results;
}
class _Result {
String _title;
String _link;
String _published;
String _summary;
List<String> _categories = [];
_Result(result) {
_title = result['title'];
_link = result['link'];
_published = result['published'];
_summary = result['summary'];
for (int i = 0; i < result['category'].length; i++) {
_categories.add(result['category'][i]);
}
}
String get published => _published;
String get title => _title;
String get link => _link;
String get summary => _summary;
List<String> get categories => _categories;
}
These code didn't work. I know I am doing it wrong, but my problem will be solved if either of the following question is answered -
how could I convert AtomFeed to Json?
Or change in model that could reflect the feed without converting it to Json.
Any help will be highly appreciated
With this you already have an object that could reflect the feed:
AtomFeed atomFeed = AtomFeed.parse(response.body);
AtomFeed

How to get Distinct List

I found online soluton like this:
import 'package:queries/collections.dart';
void main() {
List<String> list = ["a", "a", "b", "c", "b", "d"];
var result = new Collection(list).distinct();
print(result.toList());
}
But, I don't know how to convert var result back to List<Widget>.
There is a way that is a lot easier and does not require any additional imports.
You can convert your List to a Set which inherently only contains distinct elements and then convert that Set back to a List.
If you are using Dart 2.3 or higher (environment: sdk: ">=2.3.0 <3.0.0"), you can use the following idiomatic version:
List<String> list = ['a', 'a', 'b', 'c', 'b', 'd'];
List result = [...{...list}];
The ... spread operator for iterables was just introduced with Dart 2.3.
Otherwise, you can just use old syntax:
List<String> list = ["a", "a", "b", "c", "b", "d"];
List result = list.toSet().toList();
Thank you for your answer,
Here is the full code, i try to modify your method but not working.
(Works only in print)
Future<List<List<Widget>>> getList(List<int> list, String column) async {
List<Widget> list1 = List();
List<Widget> list2 = List();
List<Widget> list3 = List();
//test
List<String> testlista = List();
testlista.add(result[0][column].toString());
List<List<Widget>> listFromDB = [list1, list2, list3];
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'books.db');
Database database = await openDatabase(path, version: 1);
for (int i = 0; i < list.length; i++) {
var result = await database.rawQuery(
'SELECT DISTINCT $column FROM planner WHERE id = ${list[i]}');
//here polulate new List
testlista.add(result[0][column].toString());
if (list[i] < 18) list1.add(_item(result[0][column].toString()));
if (list[i] > 17 && list[i] < 50)
list2.add(_item(result[0][column].toString()));
if (list[i] > 49) list3.add(_item(result[0][column].toString()));
}
//Now this give me corect print list without duplicate!!!
for (int i = 0; i < testlista.length-1; i++) {
print('FROM DELETE method: '+ deleteDuplicate(testlista)[i]);
}
await database.close();
return listFromDB;
}
//Method for removingDuplicate
List<String> deleteDuplicate(List<String> lista) {
// List<String> result = Set.from(lista).toList();
List<String> result = {...lista}.toList();
return result;
}