未为类型定义运算符“[]”尝试定义运算符“[]”

时间:2021-03-13 19:53:20

标签: flutter dart

我正在学习开发,我知道某处有一个简单的错误,但我已经被冻结了几个小时。

我的模型

class MonthModel {
  String name;
  
  List day = [];
  List facture = [];

  MonthModel({this.name});
  MonthModel.fromJson(Map<dynamic, dynamic> map)
  : name = map['payments'] ?? '';

  
}

my repository:

class RealtimeRepository{
  //const RealtimeRepository();

  

  Future<List<MonthModel>> getMonth() async {
    DatabaseReference databaseReference =
    FirebaseDatabase.instance.reference().child("payments");
    var monthSnapshot = await databaseReference.once();
    List<MonthModel> month = [];
    print(month);
    monthSnapshot.value.entries.forEach((e) {
      print(e);
      MonthModel data = MonthModel.fromJson(e.value);
      month.add(data);
      
    });
    print(month.length);
    return month;
  }

我的建设者:

class BuildView1 extends StatelessWidget {
  var lists =  RealtimeRepository().getMonth();
  //print(lists);
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 10,
      itemBuilder: (BuildContext context, int index) {
        return ListTile(title: Text(lists[]);  <--------------PROBLEM
      },
      
    );
  }
}

我得到的不是 List,而是 'Future 为什么?

1 个答案:

答案 0 :(得分:0)

您必须使用 FutureBuilder 才能在 Future 完成后显示数据:

class BuildView1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<MonthModel>>(
        future: RealtimeRepository().getMonth(),
        builder: (context, snapshot) {
          // Wait for snapshot to complete
          if (snapshot.connectionState == ConnectionState.done &&
              snapshot.hasData) {
            final list = snapshot.data;
            return ListView.builder(
              itemCount: list.length,
              itemBuilder: (context, index) {
                return ListTile(title: Text(list[index]));
              },
            );
          } else {
            return CircularProgressIndicator();
          }
        });
  }
}