[英]Is it possible to make a If else statment in an Widget in Flutter
Is it possible to make an If else statement in a widget?是否可以在小部件中创建 If else 语句? I am reading the phone number in my app and if it is present I want to see that it is present but if it is not present I want to build another widget for it with a different navigation.
我正在阅读我的应用程序中的电话号码,如果它存在,我想查看它是否存在,但如果它不存在,我想为它构建另一个具有不同导航的小部件。 When I tested it, it always came out that the phone number is not present, so it always came to the else.
当我测试它时,它总是显示电话号码不存在,所以它总是出现在else中。 Where is my error?
我的错误在哪里?
class _NewTest extends State<NewTest> {
static String mmobileNumber = '';
List<SimCard> _simCard = <SimCard>[];
var list;
String text = "Mobilnumber is empty";
@override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 3), () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => Carrier_Info()),
(_) => false);
});
MobileNumber.listenPhonePermission((isPermissionGranted) {
if (isPermissionGranted) {
initMobileNumberState();
} else {}
});
initMobileNumberState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initMobileNumberState() async {
if (!await MobileNumber.hasPhonePermission) {
await MobileNumber.requestPhonePermission;
return;
}
String mobileNumber = '';
// Platform messages may fail, so we use a try/catch PlatformException.
try {
mobileNumber = await MobileNumber.mobileNumber;
_simCard = await MobileNumber.getSimCards;
} on PlatformException catch (e) {
debugPrint("Failed to get mobile number because of '${e.message}'");
}
if (!mounted) return;
setState(() async {
var re = RegExp(r'\+[^]*');
mmobileNumber = mobileNumber.replaceRange(0, 3, ''.replaceAll(re, '+'));
print('Hier ist die mobilnummer');
print(mmobileNumber);
});
}
Widget fillCards() {
List<Widget> widgets = _simCard
.map((SimCard sim) => Text(
'Sim Card Number: (${sim.countryPhonePrefix}) - ${sim.number}\nCarrier Name: ${sim.carrierName}\nCountry Iso: ${sim.countryIso}\nDisplay Name: ${sim.displayName}\nSim Slot Index: ${sim.slotIndex}\n\n'))
.toList();
return Column(children: widgets);
}
bool _loading = true;
@override
Widget build(BuildContext context) {
if (mmobileNumber == null) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
backgroundColor: Color.fromRGBO(35, 31, 32, 1),
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/images/test.png',
fit: BoxFit.contain,
height: 55,
)
],
),
),
body: Center(
child: _loading
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color.fromRGBO(35, 31, 32, 1),
),
backgroundColor: Colors.grey[200],
strokeWidth: 5,
),
Text(" "),
Text("Data is loaded and MobileNumber is not empty.",
style: TextStyle(fontSize: 20)),
Text(mmobileNumber),
],
)
: Text("Press button to download"),
),
));
} else {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
backgroundColor: Color.fromRGBO(35, 31, 32, 1),
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/images/autokontor.png',
fit: BoxFit.contain,
height: 55,
)
],
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(" "),
Text("MobileNumber is empty.", style: TextStyle(fontSize: 20)),
],
)),
));
}
}
}
Thanks for your help I have found a solution:感谢您的帮助,我找到了解决方案:
@override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 1), () {
if (mmobileNumber.length < 1) {
print("is empty");
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => NoMobileNumber()),
(_) => false);
} else if (list == null) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => NoInternet()),
(_) => false);
} else {
print(_loadHtml3(String));
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => Test(mmobileNumber, mmobileNumber,
list[1][0], _loadHtml2(String), _loadHtml3(String))),
(_) => false);
}
});
MobileNumber.listenPhonePermission((isPermissionGranted) {
if (isPermissionGranted) {
initMobileNumberState();
} else {}
});
futureAlbum = fetchAlbum();
initMobileNumberState();
}
I just made the IF else statments in the init.我刚刚在 init 中做了 IF else 语句。 Might not be the smartest solution but it works for me.
可能不是最聪明的解决方案,但它对我有用。
You can use the ternary operator for this.您可以为此使用三元运算符。
phoneNumber? Container(): Text("Not Present")
Yes, instead of conditionally return MaterialApp widget you can conditionally render widget in the child.是的,您可以有条件地在子级中渲染小部件,而不是有条件地返回 MaterialApp 小部件。 See bellow example:
见下面的例子:
Container(
child : if(mobileNumber)
Text()
else
Container(),
color: Colors.red
);
Perhaps, using a state management approach will be better solution on conditional rendering, see Flutter State Management Approach也许,使用 state 管理方法将是条件渲染的更好解决方案,请参阅Flutter State 管理方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.