【问题标题】:Flutter converting String to BooleanFlutter 将字符串转换为布尔值
【发布时间】:2023-01-18 10:44:36
【问题描述】:
我有一个细绳我想转换成布尔值下面是字符串的样子
String isValid = "false";
字符串 isValid 可以是 true 或 false
有没有办法我可以直接转换这个细绳对布尔值.我试过 Sample questions and solutions 但他们只是转换硬编码的字符串,例如大多数答案只是当字符串是 true
【问题讨论】:
标签:
string
flutter
dart
boolean
【解决方案1】:
在我的头上,您可以根据自己的需要为 string 数据类型创建一个扩展方法,通过各种需求检查和自定义异常来美化您想要的功能。这是一个例子:
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);
}
}
在此示例中,我在 main() 方法中创建了一个名为 isValid 的变量,其中包含一个 string 值。但是,仔细看看我是如何使用下面几行声明的 extension 的权力将 string 值解析为 bool 值的。
同理,可以访问新创建的string-extension方法toBoolean()从任何地方。请记住,如果您不在toBoolean()扩展已创建,不要忘记导入正确的引用。
奖金提示:
您还可以访问toBoolean()像这样,
bool alternateValidation = "true".toBoolean();
编码愉快?
【解决方案2】:
此示例可以为您工作,如果是 false 或 true:
String isValid = "true";
bool newBoolValue = isValid.toLowerCase() != "false";
print(newBoolValue);
【解决方案3】:
您可以使用这样的扩展
bool toBoolean() {
String str = this!;
return str != '0' && str != 'false' && str != '';
}
【解决方案4】:
首先
您应该将字符串设为小写,以防止对字符串进行两次检查
然后你可以检查字符串是否等于“true”并将结果保存到 bool 变量,如下所示:
String isValidString = "false"; // the boolean inside string
bool isValid = isValidString.toLowerCase() == 'true'; // check if true after lowercase
print("isValid=$isValid"); // print the result
【解决方案5】:
这个问题我开了个PR,相信以后可以做一些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..
}
}
参考
https://github.com/dart-lang/sdk/pull/51026