Tom Walsh
Tom Walsh

Reputation: 129

How to pass specific ListTile variables to new page route onTap?

My code builds a ListView of ListTiles, with each ListTile getting data from a cloud firestore database.

When I activate the onTap of a ListTile I would like to route to a new page and pass the specific data for that tile to the new page.

The page which I am building the list view on I have passed variables to without problems, however I cannot get the same method to work on this page.

I am fairly new to flutter and dart. My first assumption is that maybe it requires a stateful widget in order to accomplish this? However I am not exactly sure how to implement this.

import 'package:flutter/material.dart';

import 'package:menu/screens/menu/detail.dart';

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

class Menu extends StatelessWidget {
    final String barcode;

  // receive data from the FirstScreen as a parameter
  Menu({Key key, @required this.barcode}) : super(key: key);

  Widget _buildListItem(BuildContext context, DocumentSnapshot document) {
    return ListTile(
      leading: Icon(Icons.fastfood),
      title: Text(document['item'] ?? '*name*'),
      subtitle: Text( document['description'] ?? '*description*'),
      isThreeLine: true,
      onTap: (){
        Navigator.push(
            context,
            MaterialPageRoute(
            builder: (context) => Detail(),
        ),);
        },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Menu'),
      ),
      body: StreamBuilder(
          stream: Firestore.instance.collection(barcode).snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) return const Text('loading...');
            return ListView.builder(
              itemExtent: 80.0,
              itemCount: snapshot.data.documents.length,
              itemBuilder: (context, index) =>
                  _buildListItem(context, snapshot.data.documents[index]),
            );
          }),
    );
  }
}

Upvotes: 0

Views: 2705

Answers (1)

Ski
Ski

Reputation: 14497

Pass document as parameter to Detail

    Navigator.push(
        context,
        MaterialPageRoute(
        builder: (context) => Detail(document), // <-- document instance
    ),);

Detail widget of course need to take document as parameter:

class Detail extends ... {
  Detail(this.document);
  final DocumentSnapshot document;
}

as described in https://flutter.io/docs/cookbook/navigation/passing-data

Upvotes: 1

Related Questions