PKirby
PKirby

Reputation: 879

Flutter multiple if-statement

I have the following multiple if-statement in my flutter app:

        Text(text1).toString()==Text('Info and Comms').toString()?(snapshot.data.documents[8]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Media').toString()?(snapshot.data.documents[10]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Utilities').toString()?(snapshot.data.documents[16]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Education').toString()?(snapshot.data.documents[4]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Repairs').toString()?(snapshot.data.documents[13]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Domestic Help').toString()?(snapshot.data.documents[3]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Transport').toString()?(snapshot.data.documents[15]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Manufacturing').toString()?(snapshot.data.documents[9]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Mining').toString()?(snapshot.data.documents[11]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Supply Chain').toString()?(snapshot.data.documents[14]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Government').toString()?(snapshot.data.documents[6]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Financial and Business Services').toString()?(snapshot.data.documents[5]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Construction').toString()?(snapshot.data.documents[2]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Agriculture').toString()?(snapshot.data.documents[1]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Wholesale and Retail Trade').toString()?(snapshot.data.documents[17]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Accomodation').toString()?(snapshot.data.documents[0]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Health Social and Personal').toString()?(snapshot.data.documents[7]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Movement').toString()?(snapshot.data.documents[12]['desc'].toString()).replaceAll("/n", "\n"):
        Text('Data not found').toString(),

When deploying on my mobile device, it works perfect but after launching on Play Store, it returns the first statement regardless.

Any idea why this is now broken and where to start fixing?

*****EDIT*****

Added Category Page content where if-statement is located. Original CategoryPage Code:

 class CategoryPage extends StatelessWidget {

  final String text1;
  final String text2;
  final String text3;
  CategoryPage(
      {Key key,
      @required this.text1,
      @required this.text2,
      @required this.text3})
      : super(key: key);


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(text2),
        centerTitle: true,
        backgroundColor: Colors.grey,
      ),
      body: ListView(shrinkWrap: true, children: <Widget>[
        Container(
            child: ListTile(
              title: Text(
                'Current Level ' + text3.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Text(text3).toString() == Text("5").toString()
                        ? Colors.red[900]
                        : Text(text3).toString() == Text("4").toString()
                            ? Colors.orange[900]
                            : Text(text3).toString() == Text("3").toString()
                                ? Colors.brown[300]
                                : Text(text3).toString() == Text("2").toString()
                                    ? Colors.blue[300]
                                    : Text(text3).toString() == Text("1").toString()
                                        ? Colors.green[300]
                                        : Colors.black,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
           Container(
            child: ListTile(
              title: Text(
                text1.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        Container(
        alignment: Alignment.topLeft,
        padding: const EdgeInsets.all(8.0),
        child: StreamBuilder(
          stream: Text(text3).toString() == Text('1').toString()
              ? Firestore.instance.collection('Level1').snapshots()
              : Text(text3).toString() == Text('2').toString()
                  ? Firestore.instance.collection('Level2').snapshots()
                  : Text(text3).toString() == Text('3').toString()
                      ? Firestore.instance.collection('Level3').snapshots()
                      : Text(text3).toString() == Text('4').toString()
                          ? Firestore.instance.collection('Level4').snapshots()
                          : Text(text3).toString() == Text('5').toString()
                              ? Firestore.instance
                                  .collection('Level5')
                                  .snapshots()
                              : Firestore.instance
                                  .collection('Level1')
                                  .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Text('Loading data ...');
            } else {
              return Text(
                //snapshot.data.documents[0]['desc'].toString(),
                Text(text1).toString()==Text('Info and Comms').toString()?(snapshot.data.documents[8]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Media').toString()?(snapshot.data.documents[10]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Utilities').toString()?(snapshot.data.documents[16]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Education').toString()?(snapshot.data.documents[4]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Repairs').toString()?(snapshot.data.documents[13]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Domestic Help').toString()?(snapshot.data.documents[3]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Transport').toString()?(snapshot.data.documents[15]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Manufacturing').toString()?(snapshot.data.documents[9]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Mining').toString()?(snapshot.data.documents[11]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Supply Chain').toString()?(snapshot.data.documents[14]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Government').toString()?(snapshot.data.documents[6]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Financial and Business Services').toString()?(snapshot.data.documents[5]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Construction').toString()?(snapshot.data.documents[2]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Agriculture').toString()?(snapshot.data.documents[1]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Wholesale and Retail Trade').toString()?(snapshot.data.documents[17]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Accomodation').toString()?(snapshot.data.documents[0]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Health Social and Personal').toString()?(snapshot.data.documents[7]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Movement').toString()?(snapshot.data.documents[12]['desc'].toString()).replaceAll("/n", "\n"):
                Text('Data not found').toString(),
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.normal),
                textAlign: TextAlign.left,
              );
            }
          },
        ),
        decoration: BoxDecoration(border: Border.all(color: Colors.grey[300])),
      ),]
      ));
  }

}

*****UPDATE***** After simplifying if-statement following Yann39 advice - code works perfectly fine on my side when deploying from Visual Code onto my phone but still does not work when downloading the app from Google Play Store.

Updated CategoryPage:

class CategoryPage extends StatelessWidget {

  final String text1;
  final String text2;
  final String text3;
  CategoryPage(
      {Key key,
      @required this.text1,
      @required this.text2,
      @required this.text3})
      : super(key: key);


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(text2),
        centerTitle: true,
        backgroundColor: Colors.grey,
      ),
      body: ListView(shrinkWrap: true, children: <Widget>[
        Container(
            child: ListTile(
              title: Text(
                'Current Level ' + text3.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Text(text3).toString() == Text("5").toString()
                        ? Colors.red[900]
                        : Text(text3).toString() == Text("4").toString()
                            ? Colors.orange[900]
                            : Text(text3).toString() == Text("3").toString()
                                ? Colors.brown[300]
                                : Text(text3).toString() == Text("2").toString()
                                    ? Colors.blue[300]
                                    : Text(text3).toString() == Text("1").toString()
                                        ? Colors.green[300]
                                        : Colors.black,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
           Container(
            child: ListTile(
              title: Text(
                text1.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        Container(
        alignment: Alignment.topLeft,
        padding: const EdgeInsets.all(8.0),
        child: StreamBuilder(
          stream: Text(text3).toString() == Text('1').toString()
              ? Firestore.instance.collection('Level1').snapshots()
              : Text(text3).toString() == Text('2').toString()
                  ? Firestore.instance.collection('Level2').snapshots()
                  : Text(text3).toString() == Text('3').toString()
                      ? Firestore.instance.collection('Level3').snapshots()
                      : Text(text3).toString() == Text('4').toString()
                          ? Firestore.instance.collection('Level4').snapshots()
                          : Text(text3).toString() == Text('5').toString()
                              ? Firestore.instance
                                  .collection('Level5')
                                  .snapshots()
                              : Firestore.instance
                                  .collection('Level1')
                                  .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Text('Loading data ...');
            } else {
              return Text(DocumentUtils.getDocumentDescriptionFromTitle(snapshot, text1.toString()),style: TextStyle(
                     color: Colors.white,
                     fontSize: 15,
                     fontWeight: FontWeight.normal),
                 textAlign: TextAlign.left,);
            }
          },
        ),
        decoration: BoxDecoration(border: Border.all(color: Colors.grey[300])),
      ),]
      ));
  }

}

class DocumentUtils {

  static String getDocumentDescriptionFromTitle(AsyncSnapshot snapshot, String title) {
    var map = {
      'Info and Comms':8,
      'Media':10,
      'Utilities':16,
      'Education':4,
      'Repairs':13,
      'Domestic Help':3,
      'Transport':15,
      'Manufacturing':9,
      'Mining':11,
      'Supply Chain':14,
      'Government':6,
      'Financial and Business Services':5,
      'Construction':2,
      'Agriculture':1,
      'Wholesale and Retail Trade':17,
      'Accomodation':0,
      'Health Social and Personal':7,
      'Movement':12,
    };
    return map[title] != null ? snapshot.data.documents[map[title]]['desc'].toString().replaceAll("/n", "\n") : 'Data not found';
  }

}

*****UPDATE******

After the above if-statement simplify, the correct category discriptions are displayed, but now it only returns Collection 'Level1' from Firestore :

stream: Text(text3).toString() == Text('1').toString()
              ? Firestore.instance.collection('Level1').snapshots()
              : Text(text3).toString() == Text('2').toString()
                  ? Firestore.instance.collection('Level2').snapshots()
                  : Text(text3).toString() == Text('3').toString()
                      ? Firestore.instance.collection('Level3').snapshots()
                      : Text(text3).toString() == Text('4').toString()
                          ? Firestore.instance.collection('Level4').snapshots()
                          : Text(text3).toString() == Text('5').toString()
                              ? Firestore.instance
                                  .collection('Level5')
                                  .snapshots()
                              : Firestore.instance
                                  .collection('Level1')
                                  .snapshots(),

The above multiple if-statement works fine when deploying the app on my device, it is only when installing the app from Play Store which gives me these issues with the multiple if-statements.

Upvotes: 1

Views: 1571

Answers (1)

Yann39
Yann39

Reputation: 15719

Maybe it does not answer directly your question (it is too long for a comment) but I'm not sure to understand why you are using Text(text1).toString() == Text('text').toString() instead of text1 == 'text' directly ?

Also note that Text(text3).toString() will return the string "Text(text3)", not the contained text. If you want to get the contained text use Text(text3).data. But once again you shouldn't have to create Text widgets here, text1 == 'text' should do the job, it is much more simple and performant.

I would have also simplified thoses if repetitions into a function, for example (assuming that you don't have the documents titles in snapshot.data.documents then you would not need the map to do the mapping) :

class DocumentUtils {

  static String getDocumentDescriptionFromTitle(AsyncSnapshot<YourObject> snapshot, String title) {
    var map = {
      'Info and Comms':8,
      'Media':10,
      'Utilities':16,
      'Education':4,
      'Repairs':13,
      'Domestic Help':3,
      'Transport':15,
      'Manufacturing':9,
      'Mining':11,
      'Supply Chain':14,
      'Government':6,
      'Financial and Business Services':5,
      'Construction':2,
      'Agriculture':1,
      'Wholesale and Retail Trade':17,
      'Accomodation':0,
      'Health Social and Personal':7,
      'Movement':12,
    };
    return map[title] != null ? snapshot.data.documents[map[title]]['desc'].toString().replaceAll("/n", "\n") : 'Data not found';
  }

}

So that in your widget you just have to call DocumentUtils.getDocumentDescriptionFromTitle(snapshot, text1).

If you have the documents titles in your snapshot.data.documents then it would be something like :

class DocumentUtils {

  static String getDocumentDescriptionFromTitle(AsyncSnapshot<YourObject> snapshot, String title) {
    return snapshot.data.documents.firstWhere((Document d) => d.title == title)['desc'].replaceAll("/n", "\n");
  }

}

Upvotes: 1

Related Questions