Kanta Yamada
Kanta Yamada

Reputation: 45

The argument type 'Stream<dynamic>' can't be assigned to the parameter type 'Stream<QuerySnapshot<Object?>>?'

I am a beginner at Flutter and creating a real-time chat app.

The error has occurred stream: usersStream,line which says "The argument type 'Stream<dynamic>' can't be assigned to the parameter type 'Stream<QuerySnapshot<Object?>>?'."

Widget searchUsersList() {
    return StreamBuilder<QuerySnapshot>(
      stream: usersStream,
      builder: (context, snapshot) {
        return snapshot.hasData
            ? ListView.builder(
                shrinkWrap: true,
                itemCount: snapshot.data!.docs.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot ds = snapshot.data!.docs[index];
                  return Image.network(ds["imgUrl"]);
                },
              )
            : Center(
                child: CircularProgressIndicator(),
              );
      },
    );
  }

I am using VScode to develop and Below is error phot and full code

screenshot of VScode

Full error says

lib/views/home.dart:34:15: Error: The argument type 'Stream' can't be assigned to the parameter type 'Stream<QuerySnapshot<Object?>>?'.

Full Code <home.dart>

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:messenger_clone/services/auth.dart';
import 'package:messenger_clone/services/database.dart';
import 'package:messenger_clone/views/signin.dart';
import 'package:flutter/src/material/icons.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

final databaseReference = FirebaseFirestore.instance;

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

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

class _HomeState extends State<Home> {
  bool isSearching = false;
  late Stream usersStream;

  TextEditingController searchUserNameEdittingController =
      TextEditingController();

  onSearchBtnClick() async {
    isSearching = true;
    setState(() {});
    usersStream = await DatabaseMethods()
        .getUserByUserName(searchUserNameEdittingController.text);
  }

  Widget searchUsersList() {
    return StreamBuilder<QuerySnapshot>(
      stream: usersStream,
      builder: (context, snapshot) {
        return snapshot.hasData
            ? ListView.builder(
                shrinkWrap: true,
                itemCount: snapshot.data!.docs.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot ds = snapshot.data!.docs[index];
                  return Image.network(ds["imgUrl"]);
                },
              )
            : Center(
                child: CircularProgressIndicator(),
              );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("messenger clone"),
        actions: [
          InkWell(
            onTap: () {
              AuthMethods().signOut().then((s) {
                Navigator.pushReplacement(
                    context, MaterialPageRoute(builder: (context) => SignIn()));
              });
            },
            child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16),
                child: Icon(Icons.exit_to_app)),
          )
        ],
      ),
      body: Container(
        margin: EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          children: [
            Row(
              children: [
                isSearching
                    ? GestureDetector(
                        onTap: () {
                          isSearching = false;
                          searchUserNameEdittingController.text = "";
                          setState(() {});
                        },
                        child: Padding(
                            padding: EdgeInsets.only(right: 12),
                            child: Icon(Icons.arrow_back)),
                      )
                    : Container(),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.symmetric(horizontal: 16),
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    decoration: BoxDecoration(
                        border: Border.all(
                            color: Colors.grey,
                            width: 1,
                            style: BorderStyle.solid),
                        borderRadius: BorderRadius.circular(24)),
                    child: Column(children: [
                      Row(
                        children: [
                          Expanded(
                              child: TextField(
                            controller: searchUserNameEdittingController,
                            decoration: InputDecoration(
                                border: InputBorder.none, hintText: "username"),
                          )),
                          GestureDetector(
                              onTap: () {
                                if (searchUserNameEdittingController.text !=
                                    "") {
                                  onSearchBtnClick();
                                }
                              },
                              child: Icon(Icons.search))
                        ],
                      ),
                    ]),
                  ),
                )
              ],
            ),
            searchUsersList()
          ],
        ),
      ),
    );
  }
}

====To be safe, I add here pubspec.yaml===

name: messenger_clone
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"


dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  firebase_auth: ^3.1.4
  firebase_core: ^1.8.0
  google_sign_in: ^5.2.1
  shared_preferences: ^2.0.8
  random_string: ^2.3.1
  cloud_firestore: ^2.5.4

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0


flutter:


  uses-material-design: true

=====database.dart=====

import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseMethods {
  Future addUserInfoToDB(
      String userId, Map<String, dynamic> userInfoMap) async {
    return FirebaseFirestore.instance
        .collection("users")
        .doc(userId)
        .set(userInfoMap);
  }

  Future<Stream<QuerySnapshot>> getUserByUserName(String username) async {
    return FirebaseFirestore.instance
        .collection("users")
        .where("username", isEqualTo: username)
        .snapshots();
  }
}

=====What I tried======

・delete <QuerySnapshot> from Widget

Then another error has occurred...

The getter 'docs' isn't defined for the type 'Object'.

on itemCount: snapshot.data!.docs.length,anditemBuilder: (context, index) { DocumentSnapshot ds = snapshot.data!.docs[index]; return Image.network(ds["imgUrl"]); },

As I researched it is a firebase issue also, but I am not sure which is better to solve.

Upvotes: 0

Views: 927

Answers (1)

Mahmoud
Mahmoud

Reputation: 510

Please add DatabaseMethods().getUserByUserName() Codes and details in The question.

You should pass snapshots to stream builder, check below sample :

  Stream<QuerySnapshot> getUsersStream() {
    return firestore.collection('user').snapshots();
  }

So if you do not return a snapshots in the DatabaseMethods().getUserByUserName() method, you can use usersStream.snapshots() instead of userStream.

Upvotes: 1

Related Questions