如何获取从Flutter中的地图创建的ListView的索引

时间:2019-09-14 07:55:33

标签: firebase flutter google-cloud-firestore

我有一个ListView从Firebase集合中获取数据。当我单击一个项目时,我想打印索引。例如,如果我单击列表的第二项,我想打印1.我已经搜索了但没有找到识别.map中索引的解决方案。

这是我的代码

class ItemListBottomScroll extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _firestore
          .collection('books')
          .snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return new Text('Loading...');
          default:
            return new ListView(
              scrollDirection: Axis.horizontal,
              children:
                  snapshot.data.documents.map((DocumentSnapshot document) {
                return Stack(
                  children: <Widget>[
                    Container(
                      height: 80.0,
                      width: 90.0,
                      padding: EdgeInsets.only(left: 10.0),
                      child: GestureDetector(
                        onTap: () {
                          print(document['name'] +
                              document.documentID +
                              ' bottom clicked.');
                          print('Index of the item clicked: ??????'),
                        },
                        child: new CachedNetworkImage(
                            imageUrl: document['url'],
                            placeholder: (context, url) =>
                                new CircularProgressIndicator(),
                            errorWidget: (context, url, error) =>
                                new Icon(Icons.error),
                            fit: BoxFit.cover),
                      ),
                    ),
                  ],
                );
              }).toList(),
            );
        }
      },
    );
  }
}

1 个答案:

答案 0 :(得分:1)

一种解决方法如下:

ListView(
    children: snapshot.data.documents
    .asMap()
    .map((index, value) => MapEntry(
      index, 
      Container()
    )
  ).values.toList()
);

完整样本:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance.collection('books').snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError)
            return new Text('Error: ${snapshot.error}');
          switch (snapshot.connectionState) {
            case ConnectionState.waiting: return new Text('Loading...');
            default:
              return new ListView(
                children: snapshot.data.documents
                .asMap()
                .map((index, value) => MapEntry(
                  index, 
                  Stack(
                    children: <Widget>[
                      Container(
                        height: 80,
                        width: 90,
                        padding: EdgeInsets.only(left: 10),
                        child: GestureDetector(
                          onTap: () {
                            print('${value['name']} - ${value.documentID} - bottom clicked.');
                            print('Index of the item clicked: $index');
                          },
                          child: ListTile(
                            title: new Text(value['title']),
                            subtitle: new Text(value['author']),
                          ),
                        ),
                      )
                    ],
                  )
                )
              ).values.toList()
            );
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}