0

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_auths/pages/searchservice.dart';
import 'package:flutter_auths/pages/tasks.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var queryResultSet = [];
  var tempSearchStore = [];

  initiateSearch(value) {
    if (value.length == 0) {
      setState(() {
        queryResultSet = [];
        tempSearchStore = [];
      });
    }

    var capitalizedValue =
        value.substring(0, 1).toUpperCase() + value.substring(1);

    if (queryResultSet.length == 0 && value.length == 1) {
      SearchService().searchByName(value).then((QuerySnapshot docs) {
        for (int i = 0; i < docs.documents.length; ++i) {
          queryResultSet.add(docs.documents[i].data);
        }
      });
    } else {
      tempSearchStore = [];
      queryResultSet.forEach((element) {
        if (element['Username'].startsWith(capitalizedValue)) {
          setState(() {
            tempSearchStore.add(element);
          });
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: Text('Firestore search'),
        ),
        body: ListView(children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextField(
              onChanged: (val) {
                initiateSearch(val);
              },
              decoration: InputDecoration(
                  prefixIcon: IconButton(
                    color: Colors.black,
                    icon: Icon(Icons.arrow_back),
                    iconSize: 20.0,
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  contentPadding: EdgeInsets.only(left: 25.0),
                  hintText: 'Search by name',
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(4.0))),
            ),
          ),
          SizedBox(height: 10.0),
          GridView.count(
              padding: EdgeInsets.only(left: 10.0, right: 10.0),
              crossAxisCount: 2,
              crossAxisSpacing: 4.0,
              mainAxisSpacing: 4.0,
              primary: false,
              shrinkWrap: true,
              children: tempSearchStore.map((element) {
                return buildResultCard(element);
              }).toList())
        ]));
  }
}

Widget buildResultCard(data) {
  return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
      elevation: 2.0,
      child: Container(
          child: Column(
              children: <Widget> [ Text(data['Username'],
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 20.0,
                ),
              ),
                RaisedButton(
                  onPressed: () {
                    Navigator.push(
                      data,
                      MaterialPageRoute(builder: (data) => ProfilePage()),
                    );
                  },
                  child: const Text('asd', style: TextStyle(fontSize: 12)),
                ),
              ]
          )
      )
  );
}

Here I search for a user from database then it shows me the results in cards, I added a button and by clicking on it I want to navigate the page to another page but the following error occures. this is the error and the app

So I want to click on specific user’s button and redirect the page to that user’s profile. How can I do that?

blueshoot
  • 41
  • 2
  • 9

2 Answers2

0

You are getting this error because instead of passing buildContext you are passing data. So your error gets removed if you change you code from this

Navigator.push(
   data,
   MaterialPageRoute(builder: (data) => ProfilePage()),
);

to

Navigator.push(
   context,
   MaterialPageRoute(builder: (context) => ProfilePage(username: data['Username']))
);

This is how you should pass the data to the Profile Page.

Also

Widget buildResultCard(data)

be changed to

Widget buildResultCard(context, data)

and

buildResultCard(element);

to

buildResultCard(context, element);
Ravi Garg
  • 1,378
  • 12
  • 23
  • It's not working. When I change data to context it says it's undefined. – blueshoot Aug 18 '20 at 21:31
  • Alright I changed `Widget buildResultCard(data)` to `Widget buildResultCard(BuildContext context, data)` but this way how can I use buildResultCard in GridView.count? What is the second argument? It's working when I use return `buildResultCard(context,element)` but I got the error: Duplicate GlobalKey detected in widget tree. – blueshoot Aug 18 '20 at 21:45
  • I have updated the answer. If you're getting a Duplicate GlobalKey Error, Please try to restart your IDE (Android Studio/VSCode/XCode). If it still posses error, refer to https://stackoverflow.com/questions/49371221/duplicate-globalkey-detected-in-widget-tree – Ravi Garg Aug 19 '20 at 03:48
  • thank you, it worked. How can I pass that user's uid instead of it's name? – blueshoot Aug 19 '20 at 21:58
0

First, you need to Navigate to that page with data like

Navigator.push(
   context,
   MaterialPageRoute(builder: (context) => ProfilePage(profileData: data))
);

then you need to receive that data

class ProfilePage extends StatefulWidget {
  var profileData;

  ProfilePage({this.profileData});

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

class _ProfilePageState extends State<ProfilePage> {



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(widget.profileData['username']),
      ),
    );
  }
}

You can pass and receive data in another way

Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => ProfilePage(),settings: RouteSettings(arguments: data))
);

then

    class ProfilePage extends StatefulWidget {

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

class _ProfilePageState extends State<ProfilePage> {
  var profileData;
  
  @override
  Widget build(BuildContext context) {
    profileData=ModalRoute.of(context).settings.arguments;
    return Scaffold(
      body: Center(
        child: Text(profileData['username']),
      ),
    );
  }
}
MD.FAISAL KABIR
  • 161
  • 1
  • 10
  • It's not working. When I change data to context it says it's undefined. – blueshoot Aug 18 '20 at 21:31
  • Alright I changed `Widget buildResultCard(data)` to `Widget buildResultCard(BuildContext context, data)` but this way how can I use buildResultCard in GridView.count? What is the second argument? It's working when I use return `buildResultCard(context,element)` but I got the error: Duplicate GlobalKey detected in widget tree. – blueshoot Aug 18 '20 at 21:45