I am initialising Map? data
, I am getting this error Null check operator used on a null value
initially before the data is loaded. How to avoid this error and load the data.
If I remove the null operator and initialise it with empty map Map data = {}
I am getting this error RangeError (index): Invalid value: Valid value range is empty: 0
my code
List cards = [];
Map? data;
getData(){
FirebaseFirestore.instance.collection('UserData').doc(getUid()).collection('TransactionData').get().then((value){
value.docs.forEach((element) {
cards.add(element.data());
});
setState(() {
data = cards[0];
});
});
}
@override
void initState() {
super.initState();
getData();
}
//in my build method
CardSelector(
cards: cards.map((context) => CardPage(context)).toList(),
mainCardWidth: _width,
mainCardHeight: _width * 0.63,
mainCardPadding: -16.0,
onChanged:(i){
setState(() {
data = cards[i];
});
}),
Expanded(child: AmountPage(data!))
class AmountPage extends StatelessWidget {
final Map _amount;
AmountPage(this._amount);
@override
Widget build(BuildContext context) {
print('_amount: $_amount');
var textTheme = Theme.of(context).textTheme;
var padding = EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0);
return ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: (_amount['transaction'] as List).length 1,
itemBuilder: (context, i) {
if (i == 0) {
return Padding(
padding: padding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Balance', style: TextStyle(color: Colors.black)),
SizedBox(height: 8.0),
// Text(_amount['amount']),
SizedBox(height: 24.0),
Text('Today', style: TextStyle(color: Colors.black)),
],
),
);
}
var transactions = _amount['transaction'][i - 1];
return Padding(
padding: padding,
child: Row(
children: <Widget>[
Icon(Icons.shopping_cart, size: 24.0, color: Colors.blueGrey[600]),
SizedBox(width: 16.0),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(transactions['transactionId']),
Text(transactions['transactionDate'], style: textTheme.caption)
],
),
),
Text(transactions['amount'])
],
),
);
},
);
}
}
how to overcome this issue.
Thanks in advance.
CodePudding user response:
when you call Map? data
, You should make suer it is not null, for example do this:
if(data != null){
print('${data!['something']}');
}
or :
Text('${data?['something'] ?? ''}');
CodePudding user response:
For Map? data
you need to check
if(data!=null && && data.isNotEmpty){
//do your stuff
}
For Map data = {}
case do
if(data.isNotEmpty) YourWidget();
For range error, I suspect cards[i];
try with
if(i<cards.length){
data = cards[i];
}
For future case, it is first index
if(cards.isNotEmpty){
data = cards[0];
}