Позиция списка просмотра теряется при переходе между страницами {трепетание, построитель потока, просмотр списка} - PullRequest
0 голосов
/ 20 января 2019

В моем приложении Flutter я пытаюсь реализовать listview, который получает данные в виде потока из коллекции Firestore.Большинство из них работает, как и ожидалось - я могу перенести детали документа Firestore на следующую страницу (страницу сведений), но при возврате на главную страницу приложение не запоминает позицию списка - возможно, потому что это поток?

Мне нужна ваша помощь и вклад, которые могли бы помочь мне достичь цели?Ниже приведен код для справки:

Пробовал с AutomaticKeepAliveClientMixin;все еще не получаю ожидаемых результатов.

Я с нетерпением жду возможности реализовать ключи для управления состоянием в виджетах с состоянием

Widget build(BuildContext context) {
    ListTile makeListTile(DocumentSnapshot document) => ListTile(
          contentPadding:
              EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),

      leading: Container(
        padding: EdgeInsets.only(right: 12.0),
        decoration: new BoxDecoration(
            border: new Border(
                right: new BorderSide(width: 1.0, color: Colors.white24))),
        child: Icon(Icons.notifications_active, color: Colors.white),
      ),
      title: Text(
        document['title'],
        style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
      ),
      subtitle: Text(document['shortDesc'].toString(),
          style: TextStyle(color: Colors.white)),

      trailing:
          Icon(Icons.keyboard_arrow_right, color: Colors.white, size: 30.0),
      onTap: () {
        Navigator.of(context).push(new MaterialPageRoute(
                builder: (context) => NewsDetails(document: document)));
      },
    );

final topAppBar = AppBar(
  elevation: 0.1,
  backgroundColor: Colors.teal,
  title: Text('FirestoreDemo'),
    centerTitle: true,
);

Card makeCard(DocumentSnapshot document) => Card(
      elevation: 8.0,
      margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
      child: Container(
        decoration: BoxDecoration(color: Colors.teal),
        child: makeListTile(document),
      ),
    );

Card makeUnreadCard(DocumentSnapshot document) => Card(
      elevation: 8.0,
      margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
      child: Container(
        decoration: BoxDecoration(color: Colors.deepOrangeAccent),
        child: makeListTile(document),
      ),
    );

return new Scaffold(
  appBar: topAppBar,
  drawer: new MainDrawer(labels: widget.labels),
  body: new StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance
          .collection('collecton01')
          .orderBy('date', descending: true)
          .snapshots(),
      builder:
          (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

            if (!snapshot.hasData)
            return Center(child: CircularProgressIndicator(),);
        if (snapshot.hasError) return Center (child:new Text('Error: ${snapshot.error}'));
        final int itemsCount = snapshot.data.documents.length;
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return new CircularProgressIndicator();
          default:
            return new ListView.builder(
              scrollDirection: Axis.vertical,
              controller: _scrollController,

              shrinkWrap: true,
              itemCount: itemsCount,
              itemBuilder: (BuildContext context, int index) {
                final DocumentSnapshot document =
                    snapshot.data.documents[index];

                if (document['color'] == true) {
                  return makeUnreadCard(snapshot.data.documents[index]);
                }
                return makeCard(snapshot.data.documents[index]);
              },
            );
        }
      }),
);

1 Ответ

0 голосов
/ 20 января 2019

Я подумал, что мне следует обновить пост, указав, как я решил проблему.

Я добавил ключевой атрибут в просмотр списка внутри Streambuilder, и проблема теперь решена:

key: new PageStorageKey('keying'),

См.:

  1. Управление ключами

  2. Дополнительная информация

...