How to take an array input from a formfield in flutter? - flutter

I want to enter a array like [1,2,3,4,5] in the form field and use that form value as a parameter to bubblesort function to sort the array.How to implement this in flutter?

Keep it simple and just use the builtin json parser.
Like this:
List<int> nbs = List<int>.from(json.decode('[1,2,3,4]'));

Our string:
final hi = "[1,2,3,4,5]";
The regular expression used to remove the square brackets:
final regex = RegExp(r'([\[\]])');
Our string without any brackets after replacing them with nothing:
final justNumbers = hi.replaceAll(regex, ''); // 1,2,3,4,5
Our list of strings by splitting them by commas:
List<String> strings = justNumbers.split(',');
Now we parse our strings into integers (tryParse is used so that it returns null instead of throwing an exception):
List<int> numbers = strings.map((e) => int.tryParse(e)).toList();
Final
void main() {
final hi = "[1,2,3,4,5]";
final regex = RegExp(r'([\[\]])');
final justNumbers = hi.replaceAll(regex, '');
List<String> strings = justNumbers.split(',');
List<int> numbers = strings.map((e) => int.tryParse(e)).toList();
print(numbers);
}

Related

How to convert List<int> to List<Float> with Flutter?

I have a function that returns List But in my case I want to read and display float values. However, this function is a system function I can't update it.
My question is how to convert List to List?
This is the code:
characteristic.value.listen((event) async {
var bleData = SetupModeResponse(data: event);
});
Event is by default a List. When I try to declare data as List; I got List cannot assigned to List.
I would be very thankful if you can help me.
you can use the map method on list
like that:
List<int> intList = [1, 2, 3];
List<double> doubleList = intList.map((i) => i.toDouble()).toList();
You can learn more about dart list mapping here map method
This should also work:
List<int> ints = [1,2,3];
List<double> doubles = List.from(ints);
Yo can try this method and see if it works
List<int> num = [1,2,3];
List<double> doubles = List.from(num);
Try the following code:
List<double> doubleList = event.map((i) => i.toDouble()).toList()

How to convert list of decimals to a list of hexadicimal with flutter?

actually I want to convert a list of decimal to a list of hexadicimal. I tried .toRadixString(16) But I got : The method 'toRadixString' isn't defined for the type 'List'..
this is my code:
BehaviorSubject<List<int>> _value;
Stream<List<int>> get value => Rx.merge([
_value.stream,
_onValueChangedStream,
]);
List<int> get lastValue => _value.value ?? [];
Future<Null> write(List<int> value, {bool withoutResponse = false}) async {
final type = withoutResponse
? CharacteristicWriteType.withoutResponse
: CharacteristicWriteType.withResponse;
var request = protos.WriteCharacteristicRequest.create()
..remoteId = deviceId.toString()
..characteristicUuid = uuid.toString()
..serviceUuid = serviceUuid.toString()
..writeType =
protos.WriteCharacteristicRequest_WriteType.valueOf(type.index)!
..value = value.map((e) => e.toRadixString(16)).toList();
// Uint8List(4)..buffer.asInt32List()[0]=value;
//..value = value.toRadixString(16);
I would be very thankful if you can give me a solution for converting this list from decimal or int to hexadicimal.
[1]: https://i.stack.imgur.com/MVOkQ.png
You are trying to use toRadixString on list.
as on https://api.flutter.dev/flutter/dart-core/int/toRadixString.html:
Converts this to a string representation in the given radix.
as in documentation you should use toRadixString on int.
in your case you can try this:
List get hexLastValue => _value.value.map((e) => e.toRadixString(16)).toList();

How can i convert 'X' to '*' and them compute it in dart

i am building a calculator app although its working fine but i just want to make it look like this before its is been turn into mathematical expression:
how do i achieve something like this:
'5X4' = 20
instead of using the asterisk sign '5*4' = 20
like i want to be able to replace the string 'X' in background before it's been computed
i tried this code below:
final multiply = '5X4';
final computed = multiply.replaceAll('X','*');
final result = computed;
if i run the
print(result)
but if i try
print(int.parse(result));
the console print out
Uncaught Error: FormatException: 5*4
how do i fix this?
You can use expressions package. Here is an example:
String data = "12x2÷3-2+4";
data = data.replaceAll("x", "*");
data = data.replaceAll("÷", "/");
Expression expression = Expression.parse(data);
const evaluator = ExpressionEvaluator();
var r = evaluator.eval(expression, {});
print(r.toString()); // 10.0
You should try this approach.
final multiply = '5X4';
final computed = multiply.replaceAll('X','*');
final List<String> variable1 = computed.split('*');
final result = int.parse(variable1.first) * int.parse(variable1.last);
final lastResult = '$computed = $result';
print(lastResult);
Dartpad

Extract number and separate with comma from list in Flutter

List listFinal = [];
So listFinal have values from multiple list inside like below.
[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]]
How do I make this list so that it only extract numbers and separate with comma?
End result should be like
[1113335555, 2223334555, 5553332222]
I can think of trimming or regexp but not sure how to pull this off.
many thanks.
Try this
void main() {
List<String> numberList=[];
List<List<dynamic>> demoList=[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]];
for(int i=0;i<demoList.length;i++){
numberList.addAll(demoList[i].map((e) => e.toString().split(":")[1].replaceAll("-", "")).toList());
}
print(numberList.toString());
}
Here is an example to get you started. This doesn't handle things like malformed input strings. First step is to "flatten" the list with .expand, and then for each element of the flattened iterable use a regex to extract the substring. Other options might include using .substring to extract exactly the last 12 characters of the String.
You can see this in action on dartpad.
void main() {
final input = [
['test: 111-333-5555', 'test2: 222-333-4555'],
['test3: 555-333-2222']
];
final flattened = input.expand((e) => e); // un-nest the lists
// call extractNumber on each element of the flattened iterable,
// then collect to a list
final result = flattened.map(extractNumber).toList();
print(result);
}
final _numberRegExp = RegExp(r'.*: ([\d-]+)$');
int extractNumber(String description) {
var numberString = _numberRegExp.firstMatch(description).group(1);
return int.parse(numberString.replaceAll('-', ''));
}
Let's do this in a simple way.
List<List<String>> inputList = [
["test: 111-333-5555", "test2: 222-333-4555"],
["test3: 555-333-2222"]
];
List resultList = [];
print('Input List : $inputList');
inputList.forEach((subList){
subList.forEach((element){
var temp = element.split(' ')[1].replaceAll('-', '');
resultList.add(temp);
});
});
print('Output List : $resultList');
Here I have taken your list as inputList and stored the result in resultList.
For each element of inputList we get a sub-list. I have converted the elements of that sub-list into the needed format and added those into a List.
Happy Coding :)

Is there any way to find unique values between two lists without using a loop in dart

Is there any way to find unique values between two lists without using a loop?
List<String> first = ['A','B','C','D'];
List<String> second = ['B','D'];
I need the result to be like this:
result = ['A','C'];
You can use where() with contains() methods from List:
void main() {
List<String> first = ['A','B','C','D'];
List<String> second = ['B','D'];
List<String> result = first.where((item) => !second.contains(item)).toList();
print(result); // [A, C]
}
Edit in DartPad.