flutter 如何高效地加载类型StreamBuilder的列表

dz6r00yl  于 2022-12-24  发布在  Flutter
关注(0)|答案(1)|浏览(103)

我有一个函数,其中我将StreamBuilder添加到List中,然后将这些StreamBuilder加载到Column中,这种方法确实很消耗内存,因为所有List都是一次性加载的,是否有其他方法可以实现这一点?
我的showList函数:

showList() {
    List<Widget> theList= [];
    for (CountryModel country in _allCountries) {
      theList.add(StreamBuilder(
      stream:FirebaseFirestore.instance.collection('user').doc(country.Id).snapshots(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              xModel user = UserModel.fromDoc(snapshot.data);
              return CountryWidget(
                  country: country,
                  viewer: user.id as String,);
            } else {
              return SizedBox.shrink();
            }
          }));
    }
    return theList;
  }

在我的Scaffold中,我有一个Column,我在其中使用spread操作符将列表加载到children[]中。

Column(
  children: <Widget>[
    ...showList()
  ],
),
nfs0ujit

nfs0ujit1#

请尝试以下代码:

ListView.builder(
  itemCount: _allCountries.length + _anotherList.length,
  itemBuilder: (context, index) {
    if (index >= _allCountries != true) {
      final CountryModel country = _allCountries[index];
      return StreamBuilder(
        stream: FirebaseFirestore.instance.collection('user').doc(country.Id).snapshots(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            xModel user = UserModel.fromDoc(snapshot.data);
            return CountryWidget(
              country: country,
              viewer: user.id as String,
            );
          } else {
            return SizedBox.shrink();
          }
        }
        final item = _anotherList[index];
        return widget;
      },
    );
  },
),

相关问题