简体   繁体   English

是否可以在 Flutter 的 Widget 中创建 If else 语句

[英]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.

相关问题 是否可以将 Android Fragment 转换为 Flutter Widget? - Is it possible to convert an Android Fragment into Flutter Widget? 开关-大小写表达式必须是常量表达式,我不能使用if-else语句 - Switch - case expressions must be constant expressions, I can't make the if-else statment 在 Flutter 中制作自定义小部件时,onPress 不起作用 - onPress not working when make Custom Widget in Flutter 如何在 flutter 中禁用 RadioListTile 小部件 - How to make RadioListTile widget disabled in flutter 是否可以在 Flutter 中使 RIchText 可编辑? - Is it possible to make RIchText Editable in Flutter? 是否可以从 webview 制作主屏幕小部件? - Is it possible to make home screen widget from webview? android edittext中的验证跳到else语句 - Validation in android edittext skipping to else statment 是否可以在flutter中为SliverList内的按钮实现一个可禁用的窗口小部件 - is it Possible to Implement a Dismissible widget for a button inside a SliverList in flutter 是否可以在 flutter 中使用底部抽屉小部件而不将其拉开? - Is it possible to use a bottom drawer widget without pulling it away in flutter? 你如何在 Flutter 中制作水平数字选择器小部件? - How do you make a Horizontal Number Picker Widget in Flutter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM