实时数据库的ListView问题

时间:2020-02-21 16:15:39

标签: listview flutter firebase-realtime-database

我正在尝试将我的实时数据库与flutter应用程序连接起来,以将数据下载到列表视图。尝试在列表视图上显示数据时出现问题,因为它始终显示默认文本。我在android studio的控制台上打印了数据,我看到数据已正确下载,但listview看不到它们。

我发布以下代码:

class _ReadUsersDetailsState extends State<ReadUsersDetails> {
  List<FireBaseFunction> list = [];
  DatabaseReference databaseReference =
      FirebaseDatabase.instance.reference().child("DataBase");

  @override
  void initState() {
    super.initState();
    chargeData();

    print("List: $list");
  }

  void chargeData() {
    databaseReference.once().then((DataSnapshot snap) {
      var keys = snap.value.keys;
      var data = snap.value;

      for (var key in keys) {
        FireBaseFunction fireBaseFunction =
            new FireBaseFunction(data[key]['Name'], data[key]['Surname']);
        list.add(fireBaseFunction);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('Database'),
      ),
      body: Container(
        child: createListView(),
      ),
    );
  }

  Widget createListView() {
    print("List1: $list");
    return list.length == 0
        ? new Text("Data not available")
        : new ListView.builder(
            itemBuilder: (_, index) {
              return interface(list[index].name, list[index].surname);
            },
            itemCount: list.length,
          );
  }

  Widget interface(String name, String surname) {
    return Card(
      child: Container(
        height: 90,
        child: Padding(
          padding: EdgeInsets.only(top: 20, bottom: 20),
          child: Column(
            children: <Widget>[
              new Text("Name: " + name),
              new Text("Surname: " + surname),
            ],
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

更改数据后,您需要调用setState(),以告知小部件所做的更改及其需要重新呈现。

  void chargeData() {
    databaseReference.once().then((DataSnapshot snap) {
      var keys = snap.value.keys;
      var data = snap.value;

      for (var key in keys) {
        FireBaseFunction fireBaseFunction =
            new FireBaseFunction(data[key]['Name'], data[key]['Surname']);
        list.add(fireBaseFunction);
      }
      setState(() {});
    });
  }