0

I am currently trying to display user data like from social media after a user search for another user. have a general search user function that can search user using firebase like below

  String name = '';

  List<Map<String, dynamic>> data = [];

  addDataaUser() async {
    for (var element in data) {
      FirebaseFirestore.instance.collection('users').add(element);
    }
    print('Add User Data');
  }


  @override
  void initState() {
    super.initState();
    addDataaUser();
  }

  AppBar buildSearchField() {
    return AppBar(
      title: Card(
        child: TextField(
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.search),
          ),
          onChanged: ((val) {
            setState(() {
              name = val;
            });
          }),
        ),
      ),
    );
  }

This is the ListView builder and ListTile for displaying the List of users. The onTap function leads to another page that is ProfileOthers() and in there i need the map of variable from the selected data.


//Scaffold
Scaffold(
      appBar: buildSearchField(),
      body: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection('users').snapshots(),
        builder: (context, snapshot) {
          return (snapshot.connectionState == ConnectionState.waiting)
              ? Center(
                  child: CircularProgressIndicator(),
                )
              : ListView.builder(
                  itemCount: snapshot.data!.docs.length,
                  itemBuilder: (context, index) {
                    var data = snapshot.data!.docs[index].data()
                        as Map<String, dynamic>;
                    if (data['name']
                        .toString()
                        .toLowerCase()
                        .startsWith(name.toLowerCase())) {
                      return ListTile(
                        title: Text(
                          data['name'],
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 16,
                              fontWeight: FontWeight.bold),
                        ),
                        subtitle: Text(
                          data['email'],
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 16,
                              fontWeight: FontWeight.bold),
                        ),
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(data['userImage']),
                        ),
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => ProfileOthers(data:data)),
                          );
                        },
                      );
                    }
                    return Container();
                  });
        },
      ),
    );//End of Scaffold

This is the OthersProfile page using statefullwidget

class ProfileOthers extends StatefulWidget {
  const ProfileOthers({super.key, required this.data});

  final Map<String, dynamic> data;
  // final String dataname;
  // final String dataemail;
  // final String dataimage;
  // const ProfileOthers(
  //     {super.key,
  //     required this.dataname,
  //     required this.dataemail,
  //     required this.dataimage});
  @override
  State<ProfileOthers> createState() => _ProfileOthersState();
}


Overview Search

and after user click one of the data, it should display the selected users data like this

Result (Other Users)

As you can see i don't know how to get the selected snapshot documents by [index] from the ListTile.

Anyone know how do i get the selected map data into another page to display it? or any other alternative??

Jessen Jie
  • 167
  • 1
  • 12
  • 2
    When you say onTap > Navigate to ProfileOthers(), simple pass the data Text(data['name'], see [link](https://stackoverflow.com/questions/53861302/passing-data-between-screens-in-flutter) on how to pass data to different screens – Texv Apr 30 '23 at 10:47
  • @Texv Thankyou, i sen't the data and added const ProfileOthers(Map data, {super.key}); in the otherprofile page but didn't know to access it – Jessen Jie Apr 30 '23 at 11:32
  • 1
    In the other page add the word required, so ({Key, key, required this.data}), that way it will show you an error in the first page to tell you that you must pass data. Navigator..ProfileOthers(data: data['name']) – Texv Apr 30 '23 at 11:42
  • Yes the error not showing anymore, but when i call it on second page it get undefined name i use statefull widget on second one, is that ok?. i do it like this MaterialPageRoute(builder:(context)=>ProfileOthers(datanama,dataemail,dataimage,)), and on second page like this, ProfileOthers(datanama, dataemail, dataimage); – Jessen Jie Apr 30 '23 at 15:03

1 Answers1

1
  1. Make the ProfileOthers constructor take a parameter for the type of data you want to send. In the example below, the data is defined as a Map and is set here.
class ProfileOthers extends StatelessWidget {
  const ProfileOthers({super.key, required this.data});

  final Map<String, dynamic> data;

  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}
  1. Then, use the Navigator in the ontap of your ListTile widget to push a route to the ProfileOthers widget. You put the data you want to send as a parameter in its constructor.
Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => ProfileOthers(data: data),
    ));

You can strip out the necessary information on the ProfileOthers widget by calling the appropriate key like data['email'], data['name']

Codefarmer
  • 684
  • 4
  • 8
  • Thankyou for your reply, sorry im a bit new to this.. how to make of use the parameter after it being constructed in ProfileOthers page? im getting undefined variable. I change the explanation a bit. – Jessen Jie Apr 30 '23 at 16:02
  • I realize i should access it with '${widget.data['name']}' Thankyou so much for your help, Sir can i contain or save the ${widget.data['name'] to a variable? its for further use. – Jessen Jie Apr 30 '23 at 18:03