Red Screen Error type 'String' is not a subtype of type 'int' of 'index' Flutter

119

I can only assume what the problem could be please send the logs... So

List<dynamic> members = docs[index].data()['members'];
                  String userId;
                  userId = members.elementAt(0) == myId
                      ? members.elementAt(1)
                      : members.elementAt(0);

You are using this to get the userId (String) from a dynamic list. check whether you dynamic list only contains String values before handling a value as a string. Please do this for all other occurrences of dynamic...

This error means that you cast an int to a string. That is illegal. Just check all your String occurrences.

Share:
119
Oğuzhan Sergen Eser
Author by

Oğuzhan Sergen Eser

Updated on December 19, 2022

Comments

  • Oğuzhan Sergen Eser
    Oğuzhan Sergen Eser over 1 year

    When I navigate my chat page, I see this error in red screen on emulator.

    No idea why it does not work. Does anyone know how to solve it?

    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/material.dart';
    import '../chat/chat.dart';
    
    class ChatHome extends StatefulWidget {
      @override
      _ChatHomeState createState() => _ChatHomeState();
    }
    
    class _ChatHomeState extends State<ChatHome> {
      var _db = FirebaseFirestore.instance;
      TextEditingController userController;
      final _scaffKey = GlobalKey<ScaffoldState>();
      @override
      void initState() {
        super.initState();
        userController = new TextEditingController();
        setState(() {});
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          key: _scaffKey,
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              showDialog(
                // barrierDismissible: false,
                context: context,
                builder: (context) => _buildPopUpMessage(context),
              );
            },
            splashColor: Theme.of(context).colorScheme.onSecondary,
            child: Icon(
              Icons.add,
            ),
          ),
          body: FutureBuilder(
            future: getPosts(),
            builder: (_, snapshot) {
              if (snapshot.hasData) {
                String myId = snapshot.data['id'];
                return StreamBuilder(
                  stream: getChats(myId),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      QuerySnapshot qSnap = snapshot.data;
                      List<DocumentSnapshot> docs = qSnap.docs;
                      if (docs.length == 0)
                        return Center(
                          child: Text('No Chats yet!'),
                        );
                      return ListView.builder(
                        itemCount: docs.length,
                        itemBuilder: (context, index) {
                          List<dynamic> members = docs[index].data()['members'];
                          String userId;
                          userId = members.elementAt(0) == myId
                              ? members.elementAt(1)
                              : members.elementAt(0);
                          return FutureBuilder(
                            future: getUserByUsername(userId),
                            builder: (context, _snapshot) {
                              if (_snapshot.hasData) {
                                DocumentSnapshot docSnapUser = _snapshot.data;
                                Map<String, dynamic> _user = docSnapUser.data();
                                return Card(
                                  margin: EdgeInsets.all(8.0),
                                  elevation: 8.0,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5.0),
                                  ),
                                  child: InkWell(
                                    splashColor:
                                        Theme.of(context).colorScheme.primary,
                                    onTap: () => Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => Chat(
                                                  peerId: _user["id"],
                                                  peerAvatar: _user['photoUrl'],
                                                ))),
                                    child: Container(
                                      margin: EdgeInsets.all(10.0),
                                      height:
                                          MediaQuery.of(context).size.height * 0.08,
                                      child: Center(
                                        child: Row(
                                          children: [
                                            Hero(
                                              tag: _user['photoUrl'],
                                              child: Container(
                                                width: MediaQuery.of(context)
                                                        .size
                                                        .width *
                                                    0.15,
                                                height: MediaQuery.of(context)
                                                        .size
                                                        .width *
                                                    0.15,
                                                decoration: new BoxDecoration(
                                                  shape: BoxShape.circle,
                                                  image: new DecorationImage(
                                                    fit: BoxFit.cover,
                                                    image: new NetworkImage(
                                                        _user['photoUrl']),
                                                  ),
                                                ),
                                              ),
                                            ),
                                            SizedBox(
                                              width: MediaQuery.of(context)
                                                      .size
                                                      .width *
                                                  0.02,
                                            ),
                                            SizedBox(
                                              width: MediaQuery.of(context)
                                                      .size
                                                      .width *
                                                  0.43,
                                              child: Text(
                                                _user['nickname'],
                                                style: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w600,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              }
                              return Card(
                                margin: EdgeInsets.all(8.0),
                                elevation: 8.0,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(5.0),
                                ),
                                child: Container(
                                  margin: EdgeInsets.all(10.0),
                                  height: MediaQuery.of(context).size.height * 0.08,
                                  child: Center(
                                    child: CircularProgressIndicator(
                                      valueColor: new AlwaysStoppedAnimation(
                                        Theme.of(context).colorScheme.primary,
                                      ),
                                    ),
                                  ),
                                ),
                              );
                            },
                          );
                        },
                      );
                    }
                    return Center(
                      child: CircularProgressIndicator(
                        valueColor: new AlwaysStoppedAnimation(
                          Theme.of(context).colorScheme.primary,
                        ),
                      ),
                    );
                  },
                );
              }
              return Center(
                child: CircularProgressIndicator(
                  valueColor: new AlwaysStoppedAnimation(
                    Theme.of(context).colorScheme.primary,
                  ),
                ),
              );
            },
          ),
        );
      }
    
      Widget _timeDivider(Timestamp time) {
        DateTime t = time.toDate();
        String minute =
            t.minute > 9 ? t.minute.toString() : '0' + t.minute.toString();
        String ampm = t.hour >= 12 ? "PM" : "AM";
        int hour = t.hour >= 12 ? t.hour % 12 : t.hour;
        DateTime press = DateTime.now();
        if (press.year == t.year && press.month == t.month && press.day == t.day)
          return Text(hour.toString() + ':' + minute + ' ' + ampm);
        return Text(t.day.toString() +
            '/' +
            (t.month + 1).toString() +
            '/' +
            t.year.toString());
      }
    
      Widget _buildPopUpMessage(context) {
        return Align(
          alignment: Alignment.topCenter,
          child: Container(
            padding: EdgeInsets.all(8.0),
            height: MediaQuery.of(context).size.width * .5,
            width: MediaQuery.of(context).size.width * .6,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(40),
            ),
            margin: EdgeInsets.only(bottom: 50, left: 12, right: 12, top: 50),
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  SizedBox(
                    height: MediaQuery.of(context).size.width * .1,
                    child: Center(
                      child: new RichText(
                        text: new TextSpan(
                          style: new TextStyle(
                            fontSize: 14.0,
                            color: Colors.black,
                          ),
                          children: <TextSpan>[
                            new TextSpan(
                              text: 'username',
                              style: new TextStyle(
                                  color: Theme.of(context).colorScheme.primary,
                                  fontWeight: FontWeight.bold),
                            ),
                            new TextSpan(
                              text: '@gmail.com',
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.width * .2,
                    child: Center(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Material(
                          child: TextField(
                            autofocus: true,
                            controller: userController,
                            decoration: new InputDecoration(
                              border: new OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: Theme.of(context).colorScheme.primary,
                                ),
                                borderRadius: const BorderRadius.all(
                                  const Radius.circular(10.0),
                                ),
                              ),
                              focusedBorder: new OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: Theme.of(context).colorScheme.primary,
                                ),
                                borderRadius: const BorderRadius.all(
                                  const Radius.circular(10.0),
                                ),
                              ),
                              enabledBorder: new OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: Theme.of(context).colorScheme.primary,
                                ),
                                borderRadius: const BorderRadius.all(
                                  const Radius.circular(10.0),
                                ),
                              ),
                              errorBorder: new OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: Theme.of(context).colorScheme.error,
                                ),
                                borderRadius: const BorderRadius.all(
                                  const Radius.circular(10.0),
                                ),
                              ),
                              filled: true,
                              hintText: "Type in only Username",
                              hintStyle: TextStyle(fontSize: 16.0),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.width * .1,
                    child: Center(
                      child: Align(
                        alignment: Alignment.center,
                        child: RaisedButton(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(18.0),
                          ),
                          color: Theme.of(context).colorScheme.secondary,
                          child: Text(
                            'Let\'s chat with your friend.',
                            style: TextStyle(
                                color: Theme.of(context).colorScheme.onSecondary),
                          ),
                          onPressed: () async {
                            if (userController.text.isNotEmpty) {
                              String username = userController.text.toString();
                              userController.clear();
                              QuerySnapshot doc =
                                  getUserByEmail(username + '@gmail.com');
                              if (doc.docs.length != 0) {
                                DocumentSnapshot user = doc.docs[0];
                                Map<String, dynamic> userData = user.data();
                                Navigator.pop(context);
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => Chat(
                                              peerId: userData["id"],
                                              peerAvatar: userData['photoUrl'],
                                            )));
                                print(user.data()['nickname'].toString());
                              } else {
                                showSnackPlz(context, username);
                                Navigator.pop(context);
                              }
                            } else {
                              showSnackPlzWithMessage(context, 'Empty Username');
                              Navigator.pop(context);
                            }
                          },
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    
      showSnackPlz(BuildContext context, String username) {
        final SnackBar snackMe = SnackBar(
          content: new RichText(
            text: new TextSpan(
              style: new TextStyle(
                fontSize: 14.0,
              ),
              children: <TextSpan>[
                new TextSpan(
                  text: 'User with email ',
                ),
                new TextSpan(
                  text: username,
                  style: new TextStyle(fontWeight: FontWeight.bold),
                ),
                new TextSpan(
                  text: '@gmail.com not in the database!',
                ),
              ],
            ),
          ),
        );
        _scaffKey.currentState.showSnackBar(snackMe);
      }
    
      showSnackPlzWithMessage(BuildContext context, String message) {
        final SnackBar snackMe = SnackBar(
          content: new Text(message),
        );
        _scaffKey.currentState.showSnackBar(snackMe);
      }
    
      getChats(String uid) {
        return FirebaseFirestore.instance
            .collection('messages')
            .where('members', arrayContains: uid)
            .snapshots();
      }
    
      getUserByUsername(String username) async {
        return await _db.collection('users').doc(username).get();
      }
    
      getUserByEmail(String email) async {
        return await _db.collection('users').where('email', isEqualTo: email).get();
      }
    
      Future getPosts() async {
        var firestore = FirebaseFirestore.instance;
        QuerySnapshot qn = await firestore.collection('users').get();
        return qn.docs;
      }
    }
    

    Can't find which code-row causes this.

    Tried many changes but nothing helped.

    Error SS

    Screenshot of the error

    I've been facing this problem for whole day. Being rookie in flutterworld sometimes take bunch of time.

    • glavigno
      glavigno about 3 years
      can you post flutter app logs please ? are you sure docs is of type List ?
    • Ehtisham Shahid Abbasi
      Ehtisham Shahid Abbasi about 3 years
      Post your error from your App Logs Please.
    • Oğuzhan Sergen Eser
      Oğuzhan Sergen Eser about 3 years
      [Solved]: fixed it by replacing all "myId"s with "FirebaseAuth.instance.currentUser.uid"
  • Oğuzhan Sergen Eser
    Oğuzhan Sergen Eser about 3 years
    [Already Solved]: I replaced all "myId"s with "FirebaseAuth.instance.currentUser.uid", but thanks for effort.