How to check if list contains a String, but String value is from other dart file - flutter

As you can see I have a list:
List avatarList = [
AssetsResources.VIP1,
AssetsResources.VIP2,
AssetsResources.VIP3,
AssetsResources.VIP4,
AssetsResources.VIP5,
AssetsResources.w1,
AssetsResources.w2,
];
I understand I can use method:
final bool isVIP = avatarList[index].contains('VIP');
But since AssetsResources.VIP1 is not a String like 'VIP1'but a path from other dart file, so here I have no idea how to check if the element from avatarList contains VIP value, thanks for any clue!
Update
Thanks guys for the help and sorry I didnt describe clearly, what I mean is, if
List idealList = [
'vip1',
'vip2',
'vip3',
'vip4',
'vip5',
];
so the elements in the idealList is 'vip1' but in my case the list myList is
List myList = [
AssetsResources.VIP1,
AssetsResources.VIP2,
AssetsResources.VIP3,
AssetsResources.VIP4,
AssetsResources.VIP5,
AssetsResources.w1,
AssetsResources.w2,
];
So it seems I can not directly use some methode as follows
final bool isVIP = myList[index].contains('VIP');
since the elements from myList is just a path(sorry I dont know how to call this value), could you please let me know in my case how to check if this path contains 'VIP' value? thanks!
Update
yes, AssetsResources is very simple, just store the asset path:
class AssetsResources {
/*worm avatar*/
static const String VIP1 = 'assets/worms/VIP_1.svg';
static const String VIP2 = 'assets/worms/VIP_2.svg';
static const String VIP3 = 'assets/worms/VIP_3.svg';
static const String VIP4 = 'assets/worms/VIP_4.svg';
}

The code should work fine :
class AssetsResources {
/*worm avatar*/
static const String VIP1 = 'assets/worms/VIP_1.svg';
static const String VIP2 = 'assets/worms/VIP_2.svg';
static const String VIP3 = 'assets/worms/VIP_3.svg';
static const String VIP4 = 'assets/worms/VIP_4.svg';
}
void main() {
List myList = [
AssetsResources.VIP1,
AssetsResources.VIP2,
AssetsResources.VIP3,
AssetsResources.VIP4,
];
for (final asset in myList) {
print(asset);
print(asset.contains('VIP'));
}
}
The above prints :
assets/worms/VIP_1.svg
true
assets/worms/VIP_2.svg
true
assets/worms/VIP_3.svg
true
assets/worms/VIP_4.svg
true

If I understood you correctly.
void main() {
for(var i = 0; i < avatarList.length; i++) {
String element = avatarList[i];
if(element.contains('VIP')) {
print(other.contains(element)); // true
print(other.firstWhere((e) => e.contains(element))); // 'VIP1', 'VIP2', 'VIP3', 'VIP4', 'VIP5'
}
}
}
List<String> avatarList = ['VIP1', 'VIP2', 'VIP3', 'VIP4', 'VIP5', 'w1', 'w2'];
List<String> other = ['VIP1', 'VIP2', 'VIP3', 'VIP4', 'VIP5', 'w1', 'w2'];

Related

Extract template tags {{..}} from a string in flutter

I need to extract squiggly bracketed template tags from a string. For example:
String str="Hello {{user}}, your reference is {{ref}}"
I would like a to extract the tags in-between the {{..}} into an List. For example:
["user","ref"]
How can I do this, for example with a Regx - I would need to ignore any whitespace in-side the brackets for example {{ user}} would need to return "user".
This question is exactly same as this que.. Want code for flutter dart.
You can use this regex
void main() {
RegExp re = RegExp(r'{{([^]*?)}}');
String data = "Hello {{user}}, your reference is {{ref}}";
var match = re.firstMatch(data);
if (match != null) print(match.group(1));
List something = re.allMatches(data).map((m)=>m[1]).toList();
print(something);
}
OUtput
user
[user, ref]
void main() {
String str="Hello {{user}}, your reference is {{ref}}";
List<String> lstr = getStringBetweenBracket(str);
print(lstr);
}
List<String> getStringBetweenBracket(String str) {
List<String> rstr = [];
var j = str.splitMapJoin(new RegExp(r'\{\{(.*?)\}\}'), onMatch: (e) {
if( e.group(0) != null)
return e.group(0)!.replaceAll("{{","").replaceAll("}}","")+",";
else
return "";
}, onNonMatch: (e) { return ""; });
if(j != "") {
rstr = j.split(",");
rstr.removeAt(rstr.length-1);
}
return rstr;
}
you can do this way get array of data
void main() {
String str="Hello {{user}}, your reference is {{ref}}";
var parts = str.split(' ');
print(parts);
print(parts[1]);
}
void main(){
String str = 'HelloTutorialKart.';
int startIndex = 5;
int endIndex = 13;
//find substring
String result = str.substring(startIndex, endIndex);
print(result);
}
output
Tutorial

Flutter search 'keywords' inside a String?

I want to search for a particular keyword in a String. For example, there is a string 'rajasthan' now if I want to search using 'rj', it will not detect anything, but if I search using 'raj' then it will. So what to do in this case?
My current way of searching:
String raj = 'rajasthan';
bool searchRaj = raj.contains('raj');
bool searchRJ = raj.contains('rj');
print('raj contains $searchRaj');
print('rj contains $searchRJ');
Dartpad:
https://dartpad.dev/?id=40472ce8cd82bd87ba916ea2f3e7eff9
Here you can find the example of how to achieve this.
void main() {
String raj = 'rajasthan';
String search1 = 'raj';
String search2 = 'rj';
var searchList = raj.split("").toSet();
var searchRAJ = search1.split("").toSet();
var searchRJ = search2.split("").toSet();
bool result1 = searchList.containsAll(searchRAJ);
bool result2 = searchList.containsAll(searchRJ);
print('raj contains $result1');
print('rj contains $result2');
}

RiverPod Maintaining selected item of list

I am new to riverpod and trying to figure out a state management issue.
I have one list, and two independent states which need access to the list. The states also need to select an element of the list and know what its index is. The list can totally change (add or remove elements) and the states need to determine if their selected element is still in the list and update the index accordingly (to 0 if it is not found)
Here is an example with Riverpod in pure dart:
import 'package:riverpod/riverpod.dart';
void main(List<String> arguments) {
final container = ProviderContainer();
List<String> names = ["Jack", "Adam", "Sally"];
container.read(nameListProvider.notifier).setNames(names);
//selectedName1 = "Adam"
//selectedIndex1 = 1
//selectedName2 = "Sally"
//selectedIndex2 = 2
names.remove('Adam');
container.read(nameListProvider.notifier).setNames(names);
// print(selectedName1) = "Jack" // set to 0 because selection was removed
// print(selectedIndex1) = 0
// print(selectedName2) = "Sally"
// print(selectedIndex2) = 1 // decrement to match Sally's new list index
}
final nameListProvider =
StateNotifierProvider<NameListNotifier, List<String>>((ref) {
return NameListNotifier();
});
class NameListNotifier extends StateNotifier<List<String>> {
NameListNotifier() : super([]);
setNames(List<String> names) {
state = names;
}
}
But I need the selected Name and Index to be Providers
Update: Here is my more elegant solution:
import 'package:riverpod/riverpod.dart';
void main(List<String> arguments) {
final container = ProviderContainer();
List<String> names = ["Jack", "Adam", "Sally"];
print(container.read(nameListProvider));
container.read(nameListProvider.notifier).setNames(names);
var first = container.read(selectionProvider(1).notifier);
first.setName(1);
print(container.read(selectionProvider(1)).name);
var second = container.read(selectionProvider(2).notifier);
second.setName(2);
print(container.read(selectionProvider(2)).name);
names.remove('Adam');
List<String> newNames = List.from(names);
container.read(nameListProvider.notifier).setNames(newNames);
print(container.read(selectionProvider(1)).name);
print(container.read(selectionProvider(1)).index);
print(container.read(selectionProvider(2)).name);
print(container.read(selectionProvider(2)).index);
print(container.read(nameListProvider));
}
final selectionProvider =
StateNotifierProvider.family<SelectionNotifier, Selection, int>(
(ref, page) {
return SelectionNotifier(ref.read);
});
class SelectionNotifier extends StateNotifier<Selection> {
Reader _read;
SelectionNotifier(this._read) : super(Selection());
update() {
final String? selectedName = state.name;
final List<String> names = _read(nameListProvider);
if (names == []) {
state = Selection();
return null;
}
if (selectedName == null) {
state = Selection(name: names[0], index: 0);
return;
}
int i = names.indexOf(selectedName);
if (i == -1) {
state = Selection(name: names[0], index: 0);
return;
}
state = Selection(name: selectedName, index: i);
return;
}
setName(int index) {
final List<String> names = _read(nameListProvider);
state = Selection(name: names[index], index: index);
}
}
final nameListProvider =
StateNotifierProvider<NameListNotifier, List<String>>((ref) {
return NameListNotifier(ref.read);
});
class NameListNotifier extends StateNotifier<List<String>> {
Reader _read;
NameListNotifier(this._read) : super([]);
setNames(List<String> names) {
state = names;
_read(selectionProvider(0).notifier).update();
_read(selectionProvider(1).notifier).update();
}
}
class Selection {
final String? name;
final int? index;
Selection({this.name, this.index});
}

Comparing list with another list items and returning it if it has similar items

class Object1 {
final String id;
List<Object1list> lists = [];
Object1({this.id, this.lists});
class Object1list {
final String id;
final String item;
Object1list({this.id});
}
List<String> searchlist = ['object1','object2','object3'];
What i want to do is I want to search "object1list" items for "any" matches with "searchlist" items and
return it as contain function but I don't know how, something like:
return ???.contains(???)
Can somebody help me?
The below function will help you to get matched items:
bool doSearch(List<String> searchlist, List<String> lists) {
List<String> matched = [];
for (String s in searchlist) {
if (lists.contains(s)) {
matched.add(s);
}
//else {
// return false; // Uncomment these lines if you want "lists" to contain all searched items
//}
}
return matched.length > 0; // This for 0 or more items matched
}
Other ways:
import 'package:enumerable/enumerable.dart';
void main() {
final result1 = searchlist.isNotEmpty
? searchlist.distinct().length == searchlist.length
: false;
print(result1);
// OR
final result2 = searchlist.isNotEmpty
? searchlist.toSet().length == searchlist.length
: false;
print(result2);
}
List<String> searchlist = ['object1', 'object2', 'object3', 'object2'];

add new elements to class

I've written a class like this,
class LessonCategory{final String name;
LessonCategory(this.name);
#override
String toString() {
return 'LessonCategory{name: $name}';
}
}
class Lessons {
final String lessonsName;
int discontinuity;
final LessonCategory lesscategory;
Lessons(this.lessonsName, this.discontinuity,
this.lesscategory,
);
#override
String toString() {
return 'Lessons{lessonsName: $lessonsName, discontinuity:
$discontinuity, lesscategory: $lesscategory}';
}
}
class Data {
static List<LessonCategory> categories = [
LessonCategory("a1"),
];
static List<Lessons> lessons = [
Lessons(
'Lesson A1',
0,
getCategoryFromName("a1"),
),
];
static LessonCategory getCategoryFromName(name) {
return categories.firstWhere(
(c) => c.name.toLowerCase() == name.toString().toLowerCase());
}
}
But I can't figure out how to add a new element.I already tried add,push,insert (or i missed something).
Can someone please show me the right way?
i want something like
Data.lessons.add({
lessonsName: 'Lesson Z1',
discontinuity: 0
lessCategory: 'a1'
});
just remove static syntax. if it is defined as static, it will be immutable
class Data {
static List<LessonCategory> categories = [
LessonCategory("a1"),
];
List<Lessons> lessons = [ // Remove Static syntax
Lessons(
'Lesson A1',
0,
getCategoryFromName("a1"),
),
];
static LessonCategory getCategoryFromName(name) {
return categories.firstWhere(
(c) => c.name.toLowerCase() == name.toString().toLowerCase());
}
}
but also we can correct another syntaxes
Data newData = Data();
newData.lessons.add(Lessons(
'Lesson Z1', // remove named parameters, and use positional params
0,
LessonCategory('a1'),
));
print("New Length : ${newData.lessons.length}");
Fully working code
class LessonCategory {
final String name;
LessonCategory(this.name);
#override
String toString() {
return 'LessonCategory{name: $name}';
}
}
class Lessons {
final String lessonsName;
int discontinuity;
final LessonCategory lesscategory;
Lessons(
this.lessonsName,
this.discontinuity,
this.lesscategory,
);
#override
String toString() {
return """Lessons{lessonsName: $lessonsName, discontinuity: $discontinuity, lesscategory: $lesscategory}""";
}
}
class Data {
static List<LessonCategory> categories = [
LessonCategory("a1"),
];
List<Lessons> lessons = [ // Remove Static syntax
Lessons(
'Lesson A1',
0,
getCategoryFromName("a1"),
),
];
static LessonCategory getCategoryFromName(name) {
return categories.firstWhere(
(c) => c.name.toLowerCase() == name.toString().toLowerCase());
}
#override
String toString() {
return "{${lessons.map((fruit) => print(fruit))}}";
}
}
main(List<String> args) {
Data newData = Data(); // Create instance first
newData.lessons.add(Lessons(
'Lesson Z1', // remove named parameters, and use positional params
0,
LessonCategory('a1'),
));
print("New Length : ${newData.lessons.length}");
newData.lessons.add(Lessons(
'Lesson Z1',
0,
LessonCategory('a1'),
));
print("New Length : ${newData.lessons.length}");
print("${newData.lessons}");
}
which we able to play arount in Dartpad
Result
remove the static syntax and the problem will be solved