Home > OS >  How to manage exceptions in ListView.builder?
How to manage exceptions in ListView.builder?

Time:10-24

In list whitch I'am downloading there is a parameter:

taf[index]['change']['indicator']['text']

in:

ListView.builder(
          itemCount: taf.length,
          itemBuilder: (context, index) {
            return Card(
              child: Column(
                children: [
                  Text('Indicator: '  
                      taf[index]['change']['indicator']['text']), // !!This element sometimes is present sometimes not!!
                  Text('Valid from: '   taf[index]['timestamp']['from']),
                  Text('Valid to: '   taf[index]['timestamp']['to'])
                ],
              ),
            );
          },
        ),

whitch sometimes in present in downloaded data sometimes no. My question is how to handle this to do not crash the app diring the ListView.builder function when varaying paramater is not present?

EDIT: If you know alternative for building a list view but with irregular elements let me know :)

Error screen

ListView.builder with problematic parameter

CodePudding user response:

Try this:

    ListView.builder(
          itemCount: taf.length,
          itemBuilder: (context, index) {


            var changeIndicatorText = taf[index]['change']!=null?
taf[index]['change']['indicator']!= null?
    (taf[index]['change']['indicator']['text']??""):"";
            return Card(
              child: Column(
                children: [
                  Text('Indicator: '   changeIndicatorText), 
    // !!This element sometimes is present sometimes not!!
              Text('Valid from: '   taf[index]['timestamp']['from']),
              Text('Valid to: '   taf[index]['timestamp']['to'])
            ],
          ),
        );
      },
    ),

CodePudding user response:

Use this:

       ListView.builder(
              itemCount: taf.length,
              itemBuilder: (context, index) {
                return Card(
                  child: Column(
                    children: [
Text('Indicator: '  
    taf[index]['change'] !=null &&
    taf[index]['change']['indicator'] !=null &&
    taf[index]['change']['indicator']['text'] != null?taf[index]['change']['indicator']['text']: "no")

    , // !!This element sometimes is present sometimes not!!
                          Text('Valid from: '   taf[index]['timestamp']['from']),
                          Text('Valid to: '   taf[index]['timestamp']['to'])
                        ],
                      ),
                    );
                  },
                ),
  • Related