简体   繁体   中英

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? 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. 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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM