Dart remove square brackets and add single quotation mark - flutter

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

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?

Related

convert 'Document' values' to a list in flutter (firedart)

I am building a desktop application for Windows using Flutter. I am trying to retrieve all of the documents IDs from a collection in FireStore using the package firedart (as the official FireStore package does not support Windows).
This is a simple code to get the documents from a collection:
FirebaseAuth.initialize(apiKey, VolatileStore());
Firestore.initialize(projectId);
CollectionReference stream = Firestore.instance.collection('users');
final data = await stream.get();
print(data);
The output of this print will be a list of arrays where each one has the path to the document and the values sorted inside the document.
for example:
[/users/1dfU7emalRX89z5zlfX0AQLqehq1 {url: '', name: '', height:'' , weight: '',}, /users/JF6PMb2q9Igsb56jgPRs1DGzJ0d2{url: '', name: '', height:'' , weight: '',}]
How can I print the Ids only to a list?
you can get id from this collection by convert value to string and split this string to get it
'''
'''
/// to save return id only
List<String> ids = [];
/// first store return data in List<dynamic>
List<dynamic> list = [
"/users/1dfU7emalRX89z5zlfX0AQLqehq1 {'url': '', 'name': '', 'height':'' , 'weight': '',}",
"/users/JF6PMb2q9Igsb56jgPRs1DGzJ0d2{url: '', 'name': '', 'height':'' , 'weight': '',}"
];
/// forEach element in list convert it to string
list.forEach((element) {
/// it will return part of string as '/users/1dfU7emalRX89z5zlfX0AQLqehq1 '
final String firstPartString = element.toString().split('{').first;
/// split new string by / and it the last item (it is id)
final String id = firstPartString.split('/').last;
/// adding id to ids list (trim to remove any prefix of suffix space)
ids.add(id.trim());
});
print(ids);
'''
As I found from linked package's docs, API of the library you are using is similar to the official one.
This answer might help - you can get document ID when you have a reference to the document

how to search a list by name and another list inside it

hello i have a list List<Technican> list;
where Technican has the attributes:
class Technican{
String name, status;
int nbHired, nbStar;
List<String> skills;
}
i want to search the list by name of the technician and his skills so for example
Technican(
name: "Yehya Hijazi",
nbStar: 1,
nbHired: 107,
status: 'Unavailable',
skills: [
"Replacement"
]
),
so the result must :
when I write in the text field "Yehya" the tech will appear and when I write "replacement" the technician will appear
The search text field where on Changed :
onChanged: (value) {
var trimedvalue = value.trim();
setState(() {
newList = techs
.where(
(string) =>string.name.toLowerCase().contains(trimedvalue.toLowerCase()) ||
string.skills.toString().toLowerCase().contains(trimedvalue.toLowerCase()))
)
.toList();
});
}
the first condition is working when searching name but no result on the second.
can any one help me
No need to convert the skills array to a string, you could easily do:
var trimmedvalue = 'Replacement';
var newList = techs.where(
(t) => t.name!.toLowerCase().contains(trimedvalue.toLowerCase()) ||
t.skills!.map((s) => s.toLowerCase()).contains(trimedvalue.toLowerCase())).toList();
print(newList);
Also you could change that variable called string and call it tech or something like that (for better readability); just a suggestion.
Proof that it works, run this on DartPad.dev https://gist.github.com/romanejaquez/67e3243cb80b48fa15d9347402cb5cca

Where in clause in Flutter sqflite

I'm trying to use where in clasue but i get this error:
Invalid argument [1, 2, 3] with type List Only num, String and
Uint8List are supported.
My code:
Database db = await instance.database;
List<Map> maps = await db.query('table',
where: 'categoryID in (?)', whereArgs: [ [1,2,3]]);
From this document
Particulary, lists (expect for blob content) are not supported. A
common mistake is to expect to use IN (?) and give a list of values.
This does not work. Instead you should list each argument one by one:
var list = await db.rawQuery('SELECT * FROM my_table WHERE name IN (?, ?, ?)', ['cat', 'dog', 'fish']);
But my categories can change any moment so I cant list each argument one by one.
While I understand that it could sound painful, that is unfortunately the way SQLite works and sqflite does not do any SQL parsing.
You could try the following solution that I personnaly use to build the proper number of ?.
List.filled(inArgsCount, '?').join(',')
For example:
var inArgs = ['cat', 'dog', 'fish'];
var list = await db.query('my_table',
where: 'name IN (${List.filled(inArgs.length, '?').join(',')})',
whereArgs: inArgs);

How to retrieve values from a Map within a List Flutter?

I have a list that contains single values and maps from which I want to filter data.
E.g.
List _filters = [];
String _minPrice = '';
String _maxPrice = '';
//_filters = ['Car', 'House', 6, {'minPrice': '5000', 'maxPrice': '6000'}]
I want to be able to access the minPrice and the maxPrice so that I can use them but I'm not sure how to access them.
String get minPrice {
return _minPrice;
}
String get maxPrice {
return _maxPrice;
}
The list is dynamic and at no particular order.
The use case is where a user is filtering data and one of the filters is
{'minPrice' : '5000', 'maxPrice': '6000'}
You can use list.whereType(), as per this example in order to access by type. https://coflutter.com/dart-filter-items-in-a-list-by-type/
This is complete code to get the property,
List _filters = ['Car', 'House', 6, {'minPrice': '5000', 'maxPrice': '6000'}];
final iterableMap = _filters.whereType<Map>().first;
print(iterableMap['minPrice']);
If you want to access all the maps then you can use following :
// this will return iterable
final iterableMap = _filters.whereType<Map>();
if (!iterableMap.moveNext()) {
final map = iterableMap.current();
}

Multiple arguments in sqllite in flutter

I would like to know how to pass multiple arguments to a raw query in sqllite.
My code is below
query() async {
// get a reference to the database
Database db = await DatabaseHelper.instance.database;
// raw query
List<Map> result = await db.rawQuery('SELECT * FROM my_table WHERE name=?', ['Peter']);
// print the results
result.forEach((row) => print(row));
}
In the above code i am passing one argument 'Peter' but what if I want to pass multiple arguments, for example:
List<Map> result = await db.rawQuery('SELECT * FROM my_table WHERE name=? and last_name=? and year=?', ['Peter'], ['Smith'],[2019]);
If I do the code above, I get error "Too many positional arguments: 2 expected, but 4 found." can someone show me how to pass multiple arguments to a query in sqllite flutter?
I'm assuming you're using sqflite.
You need to put all your arguments into one list and not multiple.
The code below should work like this:
List<Map> result = await db.rawQuery(
'SELECT * FROM my_table WHERE name=? and last_name=? and year=?',
['Peter', 'Smith', 2019]
);
For more examples how to use raw queries see their examples on their pub.dev page.
Or if you want to use the query function you can do it like this:
String strVal = 'str';
int intVal = 0;
String likeVal = 'str';
final List<Map<String, dynamic>> maps = await db.query('my_table',
where: "col1 LIKE ? and col2 = ? and col3 = ?",
whereArgs: ['$likeVal%', strVal, intVal],
orderBy: 'id',
limit: 10);