Is there a parsing of bool like int in Dart? - string

In Dart, there is a convenience method for converting a String to an int:
int i = int.parse('123');
Is there something similar for converting String to bool?
bool b = bool.parse('true');

Bool has no methods.
var val = 'True';
bool b = val.toLowerCase() == 'true';
should be easy enough.
With recent Dart versions with extension method support the code could be made look more like for int, num, float.
extension BoolParsing on String {
bool parseBool() {
return this.toLowerCase() == 'true';
}
}
void main() {
bool b = 'tRuE'.parseBool();
print('${b.runtimeType} - $b');
}
See also https://dart.dev/guides/language/extension-methods
To the comment from #remonh87
If you want exact 'false' parsing you can use
extension BoolParsing on String {
bool parseBool() {
if (this.toLowerCase() == 'true') {
return true;
} else if (this.toLowerCase() == 'false') {
return false;
}
throw '"$this" can not be parsed to boolean.';
}
}

No. Simply use:
String boolAsString;
bool b = boolAsString == 'true';

You cannot perform this operation as you describe bool.parse('true') because Dart SDK is a lightweight as possible.
Dart SDK is not so unified as, for example, NET Framework where all basic system types has the following unification.
IConvertible.ToBoolean
IConvertible.ToByte
IConvertible.ToChar
IConvertible.ToDateTime
IConvertible.ToDecimal
IConvertible.ToDouble
IConvertible.ToInt16
IConvertible.ToInt32
IConvertible.ToInt64
IConvertible.ToSByte
IConvertible.ToSingle
IConvertible.ToString
IConvertible.ToUInt16
IConvertible.ToUInt32
IConvertible.ToUInt64
Also these types has parse method, including Boolean type.
So you cannot to do this in unified way. Only by yourself.

Actually yes, there is!
It's as simple as
bool.fromEnvironment(strValue, defaultValue: defaultValue);
Keep in mind that you may need to do strValue.toLowerCase()

Related

Flutter converting String to Boolean

I am having a String that i would like to convert to Boolean Below is how the string looks like
String isValid = "false";
The String isValid can either be true or false
Is there a way i can directly convert this String isValid to Boolean. I have tried Sample questions and solutions but they are just converting Strings which are hard coded, for example most of the answers are just when the string is true
On top of my head, you can create an extension method for string data-type for your own need with all sorts of requirements checks and custom exceptions to beautify your desired functionalities. Here is an example:
import 'package:test/expect.dart';
void main(List<String> args) {
String isValid = "true";
print(isValid.toBoolean());
}
extension on String {
bool toBoolean() {
print(this);
return (this.toLowerCase() == "true" || this.toLowerCase() == "1")
? true
: (this.toLowerCase() == "false" || this.toLowerCase() == "0"
? false
: throwsUnsupportedError);
}
}
Here, in this example, I've created a variable named isValid in the main() method, which contains a string value. But, look closely at how I've parsed the string value to a bool value using the power with extension declared just a few lines below.
Same way, you can access the newly created string-extension method toBoolean() from anywhere. Keep in mind, if you're not in the same file where the toBoolean() extension is created, don't forget to import the proper reference.
Bonus tips:
You can also access toBoolean() like this,
bool alternateValidation = "true".toBoolean();
Happy coding 😊
This example can work for you, either if is false or true:
String isValid = "true";
bool newBoolValue = isValid.toLowerCase() != "false";
print(newBoolValue);
You can use extensions like this
bool toBoolean() {
String str = this!;
return str != '0' && str != 'false' && str != '';
}
First of All
You should make the string to lowercase to prevent check the string twice
then you can check if the string equal "true" or not and save the result to bool variable as below:
String isValidString = "false"; // the boolean inside string
bool isValid = isValidString.toLowerCase() == 'true'; // check if true after lowercase
print("isValid=$isValid"); // print the result
I opened a PR for this question, I believe that in the future it will be possible to do something native.
void main() {
print(bool.parse("true")); // true
print(bool.parse("false")); //false
print(bool.parse("TRUE")); // FormatException
print(bool.parse("FALSE")); //FormatException
print(bool.parse("True", caseSensitive: false)); // true
print(bool.parse("False", caseSensitive: false)); // false
if(bool.parse("true")){
//code..
}
}
Reference
https://github.com/dart-lang/sdk/pull/51026

Object is not bool or equals false

I'm using C# 7.0 is type pattern. I'm trying to check if an object is not bool or the bool value equals false. However, the pattern I'm currently using with a bool type is:
if (obj is bool boolean && boolean)
{
/* I'm not doing anything here */
}
else
{
DoSomething();
}
Is there a way to invert this if expression using the same type pattern?
You can also use a constant pattern:
if (!(obj is true))
{
DoSomething();
}

set ignore case value in when expression on strings

I know how to check a string is in another string
like this code.
when (myString) {
in "FirstString" -> {
// some stuff
}
in "SecondString" -> {
// some stuff
}
else -> {
// some stuff
}
}
in keyword under the hood calls this method CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false)
the question is this :
is there any way that in this case i can set ignoreCase = true ?
You can declare an ad-hoc local operator function contains for strings before when:
fun main() {
operator fun String.contains(other: String): Boolean = this.contains(other, ignoreCase = true)
when(myString) {
in "firstString" -> ...
}
}
This way that function will be invoked for in operator instead of the one declared in the standard library because it's located in the closer scope.
Note, however, that this trick works only if the original contains function is an extension. If it's a member function, it cannot be overridden with an extension.
You can use toLowerCase() function here :
when (myString.toLowerCase()) {
in "firststring" -> {
// some stuff
}
in "secondstring" -> {
// some stuff
}
else -> {
// some stuff
}
}
For the cases of when, if they're variables toLowerCase() needs to be called on each of them. But, if they're constants, simple using lower case strings will work - "firststring", "secondstring"

Eclipse JDT resolve unknown kind from annotation IMemberValuePair

I need to retrieve the value from an annotation such as this one that uses a string constant:
#Component(property = Constants.SERVICE_RANKING + ":Integer=10")
public class NyServiceImpl implements MyService {
But I am getting a kind of K_UNKNOWN and the doc says "the value is an expression that would need to be further analyzed to determine its kind". My question then is how do I perform this analysis? I could even manage to accept getting the plain source text value in this case.
The other answer looks basically OK, but let me suggest a way to avoid using the internal class org.eclipse.jdt.internal.core.Annotation and its method findNode():
ISourceRange range = annotation.getSourceRange();
ASTNode annNode = org.eclipse.jdt.core.dom.NodeFinder.perform(cu, range);
From here on you should be safe, using DOM API throughout.
Googling differently I found a way to resolve the expression. Still open to other suggestions if any. For those who might be interested, here is a snippet of code:
if (valueKind == IMemberValuePair.K_UNKNOWN) {
Annotation ann = (Annotation)annotation;
CompilationUnit cu = getAST(ann.getCompilationUnit());
ASTNode annNode = ann.findNode(cu);
NormalAnnotation na = (NormalAnnotation)annNode;
List<?> naValues = na.values();
Optional<?> optMvp = naValues.stream()
.filter(val-> ((MemberValuePair)val).getName().getIdentifier().equals(PROPERTY))
.findAny();
if (optMvp.isPresent()) {
MemberValuePair pair = (MemberValuePair)optMvp.get();
if (pair.getValue() instanceof ArrayInitializer) {
ArrayInitializer ai = (ArrayInitializer)pair.getValue();
for (Object exprObj : ai.expressions()) {
Expression expr = (Expression)exprObj;
String propValue = (String)expr.resolveConstantExpressionValue();
if (propValue.startsWith(Constants.SERVICE_RANKING)) {
return true;
}
}
}
else {
Expression expr = pair.getValue();
String propValue = (String)expr.resolveConstantExpressionValue();
if (propValue.startsWith(Constants.SERVICE_RANKING)) {
return true;
}
}
}
//report error
}
private CompilationUnit getAST(ICompilationUnit compUnit) {
final ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(compUnit);
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit unit = (CompilationUnit)parser.createAST(null);
return unit;
}

Does Dart have sprintf, or does it only have interpolation?

I would like to emulate C's sprintf("%02d", x); in Dart, but I can't find string formatting, only string interpolation.
String interpolation covers most of your needs. If you want to format numbers directly, there is also num.toStringAsPrecision().
I took a different approach to this issue: by padding the string directly, I don't have to use any libraries (mainly because the intl library seems to be discontinued):
x.toString().padLeft(2, "0");
Would be the equivalent of sprintf("%02d", x);
The intl library provides several helpers to format values.
See the API documentation at http://api.dartlang.org/docs/releases/latest/intl.html
Here is an example on how to convert a number into a two character string:
import 'package:intl/intl.dart';
main() {
var twoDigits = new NumberFormat("00", "en_US");
print(twoDigits.format(new Duration(seconds: 8)));
}
A String.format method does not currently exists but there is a bug/feature request for adding it.
Here is my implementation of String.format for Dart. It is not perfect but works good enough for me:
static String format(String fmt,List<Object> params) {
int matchIndex = 0;
String replace(Match m) {
if (matchIndex<params.length) {
switch (m[4]) {
case "f":
num val = params[matchIndex++];
String str;
if (m[3]!=null && m[3].startsWith(".")) {
str = val.toStringAsFixed(int.parse(m[3].substring(1)));
} else {
str = val.toString();
}
if (m[2]!=null && m[2].startsWith("0")) {
if (val<0) {
str = "-"+str.substring(1).padLeft(int.parse(m[2]),"0");
} else {
str = str.padLeft(int.parse(m[2]),"0");
}
}
return str;
case "d":
case "x":
case "X":
int val = params[matchIndex++];
String str = (m[4]=="d")?val.toString():val.toRadixString(16);
if (m[2]!=null && m[2].startsWith("0")) {
if (val<0) {
str = "-"+str.substring(1).padLeft(int.parse(m[2]),"0");
} else {
str = str.padLeft(int.parse(m[2]),"0");
}
}
return (m[4]=="X")?str.toUpperCase():str.toLowerCase();
case "s":
return params[matchIndex++].toString();
}
} else {
throw new Exception("Missing parameter for string format");
}
throw new Exception("Invalid format string: "+m[0].toString());
}
Test output follows:
format("%d", [1]) // 1
format("%02d", [2]) // 02
format("%.2f", [3.5]) // 3.50
format("%08.2f", [4]) // 00004.00
format("%s %s", ["A","B"]) // A B
format("%x", [63]) // 3f
format("%04x", [63]) // 003f
format("%X", [63]) //3F
Yes, Dart has a sprintf package:
https://pub.dev/packages/sprintf.
It is modeled after C's sprintf.
See a format package. It is similar to format() from Python. It is a new package. Needs testing.

Resources