Как получить данные из firebase для отображения продуктов

# #flutter #google-cloud-firestore

Вопрос:

Я пытался показать свои продукты на главной странице, взяв из коллекций firestore и показав их с помощью StreamBuilder. но то, что показывает мой рабочий стол, — это его возвращающееся «хихихихи». Я использовал правильную ссылку на коллекцию с правильным именем поля.

Ваша помощь в этом случае поможет начинающему разработчику flutter завершить свой университетский проект.

Спасибо

Вот мой код

 Container(
            height: 190,
            child: StreamBuilder(
                stream: collectionReference.snapshots(),
                builder: (BuildContext context,
                    AsyncSnapshot<QuerySnapshot> snapshot) {
                  if (snapshot.hasData) {
                    return ListView.builder(
                        scrollDirection: Axis.horizontal,
                        padding: EdgeInsets.only(left: 16, right: 6),
                        itemCount: 4,
                        itemBuilder: (context, index) {
                          children:
                          snapshot.data!.docs.map(
                            (e) => Container(
                              margin: EdgeInsets.only(right: 10),
                              height: 199,
                              width: 344,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(28),
                                color: Colors.white,
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.grey,
                                    offset: Offset(0.0, 1.0), //(x,y)
                                    blurRadius: 6.0,
                                  ),
                                ],
                              ),
                              child: Stack(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(10.0),
                                    child: Positioned(
                                      child: Image(
                                        image: AssetImage(
                                          'assets/item1.png',
                                        ),
                                        height: 200,
                                      ),
                                    ),
                                  ),
                                  Positioned(
                                    right: 20,
                                    top: 10,
                                    child: Text(
                                      e['name'],
                                      style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 25,
                                          fontFamily: 'Poppins',
                                          fontWeight: FontWeight.bold),
                                    ),
                                  ),
                                
                                  Positioned(
                                    right: 20,
                                    bottom: 10,
                                    child: Text(
                                      e['price'],
                                      style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 30,
                                          fontFamily: 'Poppins'),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                          return Center(child: Text('hi'));
                        });
                  }
                  return Center(child: Text('Empty'));
                }),
          ),
 

Ответ №1:

Проблема в том, что конструктор элементов должен возвращать, как будет построен каждый элемент в представлении списка. В настоящее время все, что вы делаете, — это сопоставляете весь снимок, а затем возвращаете виджет текста плана с приветом в нем. Попробуйте код ниже для itemBuilder:

 itemBuilder: (context, index) {
    final e = snapshot.data!.docs[index];
    return Container(
      margin: EdgeInsets.only(right: 10),
      height: 199,
      width: 344,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(28),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey,
            offset: Offset(0.0, 1.0), //(x,y)
            blurRadius: 6.0,
          ),
        ],
      ),
      child: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: Positioned(
              child: Image(
                image: AssetImage(
                  'assets/item1.png',
                ),
                height: 200,
              ),
            ),
          ),
          Positioned(
            right: 20,
            top: 10,
            child: Text(
              e['name'],
              style: TextStyle(
                  color: Colors.black,
                  fontSize: 25,
                  fontFamily: 'Poppins',
                  fontWeight: FontWeight.bold),
            ),
          ),
        
          Positioned(
            right: 20,
            bottom: 10,
            child: Text(
              e['price'],
              style: TextStyle(
                  color: Colors.black,
                  fontSize: 30,
                  fontFamily: 'Poppins'),
            ),
          ),
        ],
      ),
    );
}
 

Также имейте в виду, что ваше количество элементов равно 4, и вы, вероятно, хотите, чтобы это было:

 itemCount: snapshot.data!.docs.length
 

Комментарии:

1. Большое Тебе спасибо, Брат, я так сильно страдал, чтобы сделать это. Значит много