NoSuchMethodError: null:'length' 上的成员无效



我试图按日期筛选事务。用户选择日期后,数据将被自动过滤,但我得到了一个错误,即NoSuchMethodError:null上的无效成员:'length'。我知道列表有问题,但我不确定,因为我传递值的方式或比较日期的方式。该列表通过GET请求从DB获取数据。我测试了GET请求,并在一个无状态小部件上显示数据,它运行良好。

class BudgetDateRangePicker extends StatefulWidget {
final isSelected = <bool>[true, false];
final List<Transaction> transactions;
BudgetDateRangePicker({Key key, this.transactions}) : super(key: key);
@override
State<StatefulWidget> createState() => _BudgetDateRangePickerState();
}
class _BudgetDateRangePickerState extends State<BudgetDateRangePicker> {
DateTime _toDate = DateTime.now();
DateTime _fromDate = DateTime.utc(2020, 1, 1);
List<Transaction> trans;
Future<void> _selectDate(BuildContext context) async {
final List<DateTime> picked = await DateRangePicker.showDatePicker(
context: context,
initialLastDate: new DateTime.now(),
initialFirstDate: (new DateTime.utc(2020, 1, 1)),
firstDate: new DateTime(2015),
lastDate: new DateTime(DateTime.now().year + 2));
if (picked != null && picked.length == 2) {
setState(() {
_fromDate = picked[0];
_toDate = picked[1];
for (var item in widget.transactions) {
if (DateTime.parse(item.date).isBefore(_toDate) &&
DateTime.parse(item.date).isAfter(_fromDate)) {
trans.add(item);
}
}
});
}
}
@override
Widget build(BuildContext context) {
return Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
Container(
margin: const EdgeInsets.only(right: 10),
child: Text("From: ${DateFormat.yMMMd().format(_fromDate)}")),
Container(
margin: const EdgeInsets.only(right: 10),
child: Text("To: ${DateFormat.yMMMd().format(_toDate)}"),
),
Container(
margin: const EdgeInsets.only(right: 10),
child: RaisedButton(
color: Colors.green[200],
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(6.0),
side: BorderSide(color: Colors.white),
),
onPressed: () => _selectDate(context),
child: Text('Select date'),
),
),
ListView.separated(
separatorBuilder: (context, index) {
return Divider(color: Colors.grey[400]);
},
itemCount: trans.length, // this one has error
itemBuilder: (context, index) {
final transaction = trans[index];
return ListTile(
contentPadding: EdgeInsets.all(10),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("${transaction.category}",
style:
TextStyle(fontSize: 24, fontWeight: FontWeight.w500)),
Text("${transaction.date}",
style: TextStyle(color: Colors.grey[500], fontSize: 14)),
]),
trailing: Column(children: <Widget>[
Text("${transaction.amount}",
style: TextStyle(fontSize: 24, fontWeight: FontWeight.w500)),
]),
);
},
)
]);
}
}
Future<List<Transaction>> fetchBudgetTrans(http.Client client) async {
final response =
await client.get(Uri.parse('http://127.0.0.1:8000/budget/trans'));
return compute(parseDataBudget, response.body);
}

尝试初始化您的列表,这样如果没有应用过滤器,就不会导致空引用错误

List<Transaction> trans = [];

最新更新