'How to retrieve the selected item in the list to display its details in detail page Flutter

I have a list in a database and each item in the list has specific characteristics I want when I choose an item from the list; the detail_list page only displays the characteristics of this element by retrieving it from the firebase database.

  • the home page shows me all the customer cards
  • Detail page displays Detail card -detail card retrieve widgets from Card_Front -Card_Front shows me the details of the element I have chosen

=> how to retrieve the item selected in the list to display its details

HomePage

import 'dart:math';  
import 'package:clickable_list_wheel_view/clickable_list_wheel_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:../rotate/detail_page.dart';
import 'package:../rotate/page_notifier.dart';
import 'package:../rotate/size_config.dart';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';


class PageHome extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<PageHome> {
  bool animateCardNumber = true;
  final _scrollController = FixedExtentScrollController();
  double _itemHeight = 60;
  int _itemCount = 100;    
  @override
  void initState() {
    SystemChrome.setEnabledSystemUIOverlays([]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    FirebaseAuth auth = FirebaseAuth.instance;
    User user = auth.currentUser;
    CollectionReference _productss = FirebaseFirestore.instance
        .collection('Card')
        .doc(user.uid)
        .collection(user.uid);
    SizeConfig().init(context);
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        leading: Icon(
          Icons.arrow_back,
          color: Colors.white,
          size: SizeConfig.defaultHeight * 4,
        ),
      ),
      body: SafeArea(
          child: StreamBuilder(
        stream: _productss.snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
          if (!streamSnapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          return ClickableListWheelScrollView(
            scrollController: _scrollController,
            itemHeight: 250,
            itemCount: _itemCount,
            onItemTapCallback: (indexx) {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => DetailPage()));
            },
            child: ListWheelScrollView.useDelegate(
              controller: _scrollController,
              itemExtent: 250,
              diameterRatio: 3,
              offAxisFraction: -0.5,
              physics: FixedExtentScrollPhysics(),
              overAndUnderCenterOpacity: 0.5,
              perspective: 0.002,
              childDelegate: ListWheelChildBuilderDelegate(
                childCount: streamSnapshot.data.docs.length,
                builder: (context, index) {
                  final DocumentSnapshot documentSnapshot =
                      streamSnapshot.data.docs[0];
                  return Container(
                    padding:
                        EdgeInsets.only(bottom: SizeConfig.defaultHeight * 5),
                    child: AspectRatio(
                      aspectRatio: 5 / 3,
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            gradient: const LinearGradient(
                                colors: [
                                  Color(0xFF0000FF),
                                  Color(0XFF377CFF),
                                ],
                                begin: Alignment.bottomLeft,
                                end: Alignment.topRight,
                                stops: [0, 0.8],
                                tileMode: TileMode.clamp)),
                        child: Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: SizeConfig.defaultWidth * 2,
                              vertical: SizeConfig.defaultHeight * 2),
                          child: Column(
                            children: [
                              Expanded(
                                flex: 2,
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      "Card",
                                      style: Theme.of(context)
                                          .textTheme
                                          .headline6
                                          .copyWith(
                                              fontWeight: FontWeight.bold,
                                              color: Colors.white),
                                    ),
                                    Transform.rotate(
                                      angle: pi / 2,
                                      child: Icon(
                                        Icons.wifi,
                                        size: SizeConfig.defaultHeight * 4,
                                        color: Colors.white,
                                      ),
                                    )
                                  ],
                                ),
                              ),
                              Spacer(
                                flex: 1,
                              ),
                              Expanded(
                                flex: 2,
                                child: Row(
                                  children: [
                                    Transform.translate(
                                      offset:
                                          Offset(-SizeConfig.defaultWidth, 0),
                                     
                                    ),
                                   
                                
                                  ],
                                ),
                              ),
                              Spacer(
                                flex: 1,
                              ),
                              Expanded(
                                flex: 2,
                                child: Row(
                                  children: [
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                       
                                        Text(
                                          documentSnapshot['Name'],
                                          style: Theme.of(context)
                                              .textTheme
                                              .bodyText1
                                              .copyWith(color: Colors.white),
                                        )
                                      ],
                                    ),
                                   

                   
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                  );
                  ;
                },
              ),
            ),
          );
        },
      )
  
        ),
    );
  }
}

Detail page

import 'package:flutter/material.dart';    
import 'package:../rotate/detail_card.dart';    
import 'package:../rotate/size_config.dart';    
class DetailPage extends StatefulWidget {
  const DetailPage({Key key}) : super(key: key);

  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: Icon(
            Icons.arrow_back,
            color: Colors.white,
            size: SizeConfig.defaultHeight * 4,
          ),
        ),
        actions: [
          Icon(
            Icons.share,
            color: Colors.white,
            size: SizeConfig.defaultHeight * 4,
          )
        ],
      ),
      body: Stack(
        alignment: Alignment.topCenter,
        children: [
  
      DetailCard(),
         
        ],
      ),
    );
  }
}

Detail_card

import 'package:flutter/material.dart';
import 'back_card.dart';
import 'front_card.dart';

class DetailCard extends StatefulWidget {
  @override
  _DetailCardState createState() => _DetailCardState();
}

class _DetailCardState extends State<DetailCard> {
  bool animateCardNumber = true;


  @override
  void initState() {
    Future.delayed(Duration(milliseconds: 1000),
        () => setState(() => animateCardNumber = false));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Align(
        alignment: Alignment.center,
        child: Padding(
            padding: EdgeInsets.fromLTRB(
                SizeConfig.defaultWidth * 2,
                0,
                SizeConfig.defaultWidth * 2,
                0 > 0.462
                    ? SizeConfig.defaultHeight * 55
                    : SizeConfig.defaultHeight * 20),
            child: 
                frontWidget: FrontCard(
                  showCardNumber: true,
                  animateCardNumber: animateCardNumber,
                 
               
              )));
  }
}

Card_Front

import 'dart:math';    
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';    
import 'package:flutter/material.dart';  
import 'package:../rotate/detail_page.dart';    
import 'package:../rotate/size_config.dart';



class FrontCard extends StatefulWidget {
  final bool showCardNumber;
  bool animateCardNumber;

  final DetailPage detailPage;

  FrontCard({
    Key key,
    this.showCardNumber = false,
    this.animateCardNumber = true,

    this.detailPage,
  }) : super(key: key);

  @override
  _FrontCardState createState() => _FrontCardState();
}

class _FrontCardState extends State<FrontCard> {

  @override
  Widget build(BuildContext context) {
    FirebaseAuth auth = FirebaseAuth.instance;
    User user = auth.currentUser;
    CollectionReference _productss = FirebaseFirestore.instance
        .collection('Card')
        .doc(user.uid)
        .collection(user.uid);
    return StreamBuilder(
        stream: _productss.snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
          if (!streamSnapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          final DocumentSnapshot documentSnapshot = streamSnapshot.data.docs[0];
          return AspectRatio(
            aspectRatio: 5 / 3,
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  gradient: const LinearGradient(
                      colors: [
                        Color(0xFF0000FF),
                        Color(0XFF377CFF),
                      ],
                      begin: Alignment.bottomLeft,
                      end: Alignment.topRight,
                      stops: [0, 0.8],
                      tileMode: TileMode.clamp)),
              child: Padding(
                padding: EdgeInsets.symmetric(
                    horizontal: SizeConfig.defaultWidth * 2,
                    vertical: SizeConfig.defaultHeight * 2),
                child: Column(
                  children: [
                    Expanded(
                      flex: 2,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "Rest",
                            style: Theme.of(context)
                                .textTheme
                                .headline6
                                .copyWith(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white),
                          ),
                          Transform.rotate(
                            angle: pi / 2,
                            child: Icon(
                              Icons.wifi,
                              size: SizeConfig.defaultHeight * 4,
                              color: Colors.white,
                            ),
                          )
                        ],
                      ),
                    ),
                    Spacer(
                      flex: 1,
                    ),
                    Expanded(
                      flex: 2,
                      child: Row(
                        children: [                                                    
                          Expanded(
                              flex: 5,
                              child: 
                                Text(
                                    animateCardNumber
                                        ? documentSnapshot['Number']
                                            .substring(0, value)
                                        : documentSnapshot['Number'],
                                    textAlign: TextAlign.center,
                                    style: Theme.of(context)
                                        .textTheme
                                        .headline6
                                        .copyWith(color: Colors.white),
                                  );
                                },
                              )
                        ],
                      ),
                    ),
                    Spacer(
                      flex: 1,
                    ),
                    Expanded(
                      flex: 2,
                      child: Row(
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              
                              Text(
                                documentSnapshot['Name'],
                                style: Theme.of(context)
                                    .textTheme
                                    .bodyText1
                                    .copyWith(color: Colors.white),
                              )
                            ],
                          ),
                          
                       
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }
}


Solution 1:[1]

You have a lot of code posted here. I will take only the part that needs my help.

onItemTapCallback: (indexx) {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => 
                      // Pass the object to the details page constructor
                       DetailPage(
                        doc: streamSnapshot.data.docs[indexx]
                      )));
            },


class DetailCard extends StatefulWidget {
   final var doc;
   DetailCard({required this.doc});
    @override
   _DetailCardState createState() => _DetailCardState();
}

class _DetailCardState extends State<DetailCard> {
   bool animateCardNumber = true;

   late var doc;


  @override
  void initState() {
    Future.delayed(Duration(milliseconds: 1000),
     () => setState(() => animateCardNumber = false));
    super.initState();
    doc = widget.doc; // Access the document that was passed through the constructor here.
   }

 @override
 Widget build(BuildContext context) {
    return Align(
    alignment: Alignment.center,
    child: Padding(
        padding: EdgeInsets.fromLTRB(
            SizeConfig.defaultWidth * 2,
            0,
            SizeConfig.defaultWidth * 2,
            0 > 0.462
                ? SizeConfig.defaultHeight * 55
                : SizeConfig.defaultHeight * 20),
        child: 
            frontWidget: FrontCard(
              showCardNumber: true,
              animateCardNumber: animateCardNumber,
          )));
   }
  }

Solution 2:[2]

I was able to retrieve how many squares there are at the customer's but I could not read the data from each card and display it I replaced the results with static data=> ('aaaaaa') I want to recover the data of each card but each time an error is displayed: (An exception has occurred. NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: )) how to do ?!

import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:..t/rotate/page_notifier.dart';
import 'package:../rotate/size_config.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:simple_animations/simple_animations.dart';

class PageHome extends StatefulWidget {
  final String id;
  const PageHome({
    key,
    this.id,
  }) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<PageHome> {
  String _idDoc;
  DocumentSnapshot _res;
  String _id;
  List<QueryDocumentSnapshot> _produit = new List();
  PageNotifier _pageNotifier = PageNotifier();
  @override
  void initState() {
    _id = widget.id;
    super.initState();
    _getProductFromDatabaseUsingCategory();
  }

  _getProductFromDatabaseUsingCategory() {
    FirebaseAuth auth = FirebaseAuth.instance;
    User user = auth.currentUser;
    CollectionReference cartsRef = FirebaseFirestore.instance
        .collection('Card')
        .doc(user.uid)
        .collection(user.uid);

    cartsRef.where('ID', arrayContains: _id).get().then((res) {
      setState(() {
        _produit = res.docs;
        //_res = res as DocumentSnapshot<Object>;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        leading: Icon(
          Icons.arrow_back,
          color: Colors.white,
          size: SizeConfig.defaultHeight * 4,
        ),
      ),
      body: SafeArea(
        child: ChangeNotifierProvider(
          create: (_) => _pageNotifier,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              //HomeHeader(),
              /* Balance(
                              previousIndex: _previousIndex, currentIndex: _currentIndex), */
              _buildCardsList(),
              //_buildPageIndicator(),
            ],
          ),
        ),
      ),
    );
  }

  _buildCardsList() => Container(
        margin: EdgeInsets.fromLTRB(10, 10, 0, 10),
        height: MediaQuery.of(context).size.height - 250,
        child: Expanded(
          child: Transform(
            transform: Matrix4.identity()
              ..translate(-SizeConfig.defaultWidth * 4)
              ..rotateZ(-pi / 2),
            alignment: Alignment.center,
            child: PageView.builder(
                scrollDirection: Axis.vertical,
                itemCount: _produit.length,
                controller: _pageNotifier.pageController,
                onPageChanged: (index) => setState(() {
                      _previousIndex = _currentIndex;
                      _currentIndex = index;
                    }),
                itemBuilder: (context, index) {
                  return Consumer<PageNotifier>(
                    builder: (context, value, child) {
                      if (value.currentPage > index) {
                        double scaleFactor =
                            max(1 - (value.currentPage - index) * 0.4, 0.6);
                        double angleFactor =
                            min((value.currentPage - index) * 20, 20);
                        return Transform(
                          transform: Matrix4.identity()
                            ..setEntry(3, 2, 0.001)
                            ..scale(scaleFactor)
                            ..rotateZ(-(pi / 180) * angleFactor),
                          alignment: Alignment.center,
                          child: child,
                        );
                      }
                      return child;
                    },
                    child: GestureDetector(
                      onTap: () {
                        String id = _produit[index].id;
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => Scaffold(
                                      backgroundColor: Colors.black,
                                      appBar: AppBar(
                                        backgroundColor: Colors.black,
                                        leading: IconButton(
                                          onPressed: () =>
                                              Navigator.pop(context),
                                          icon: Icon(
                                            Icons.arrow_back,
                                            color: Colors.white,
                                            size: SizeConfig.defaultHeight * 4,
                                          ),
                                        ),
                                        actions: [
                                          Padding(
                                            padding: EdgeInsets.only(
                                                right: SizeConfig.defaultWidth *
                                                    2),
                                            child: Icon(
                                              Icons.share,
                                              color: Colors.white,
                                              size:
                                                  SizeConfig.defaultHeight * 4,
                                            ),
                                          )
                                        ],
                                      ),
                                      body: Stack(
                                        alignment: Alignment.topCenter,
                                        children: [
                                          PlayAnimation(
                                              tween:
                                                  Tween(begin: 0.2, end: 1.0),
                                              curve: Curves.easeOut,
                                              duration:
                                                  Duration(milliseconds: 200),
                                              builder: (context, child,
                                                      value) =>
                                                  Transform.scale(
                                                    scale: value,
                                                    alignment: Alignment.center,
                                                    child: Opacity(
                                                        opacity: value,
                                                        child: child),
                                                  ),
                                              child: Align(
                                                  alignment: Alignment.center,
                                                  child: Padding(
                                                    padding: EdgeInsets.fromLTRB(
                                                        SizeConfig
                                                                .defaultWidth *
                                                            2,
                                                        0,
                                                        SizeConfig
                                                                .defaultWidth *
                                                            2,
                                                        0 > 0.462
                                                            ? SizeConfig
                                                                    .defaultHeight *
                                                                55
                                                            : SizeConfig.defaultHeight *
                                                                    20 +
                                                                0 * 600),
                                                    child: Transform.scale(
                                                        scale: 0 > 0.462
                                                            ? 1 - (0 - 0.462)
                                                            : 1,
                                                        child: FlippableWidget(
                                                          frontWidget:
                                                              FrontCard(
                                                            HolderName: _produit[
                                                                "HolderName"],
                                                            Number: '5555555',
                                                            ExpiryNumber:
                                                                'aaaaaa',
                                                          ),
                                                        )),
                                                  ))),
                                        ],
                                      ),
                                    )));
                      },
                      child: Container(
                        padding: EdgeInsets.only(
                            bottom: SizeConfig.defaultHeight * 5),
                        child: FrontCard(
                          HolderName: 'aaaaaaaaaa',
                          Number: 'aaaaaa',
                          ExpiryNumber: 'aaaaaa',
                        ),
                      ),
                    ),
                  );
                }),
          ),
        ),
      );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Naj
Solution 2