Home > other >  _TypeError (type 'String' is not a subtype of type 'int' of 'index') o
_TypeError (type 'String' is not a subtype of type 'int' of 'index') o

Time:10-30

am tying to calling user to appear in profile page the app block when i fixed it i faced other problem which is this one if there any solution can help me

import 'package:flutter/foundation.dart';

class UserModel {
  String? uid;
  String? Username;
  String? email;
  String? photoUrl;
  

  UserModel(
      {this.uid, this.email, this.Username,  this.photoUrl});

  // receving data from the server
  factory UserModel.fromMap(Map) {
    return UserModel(
      uid: Map['userId'],
      Username: Map['Username'],
      email: Map['email'],
      photoUrl: Map['photoUrl'],
    );
  }

  // /// sending data to firestore
  Map<String, dynamic> toMap() {
    return {
      'userId': uid,
      'Username': Username,
      'email': email,
      'photoUrl': photoUrl,
    };
  }
}

the error picture enter image description here

CodePudding user response:

by using this :

     // receving data from the server
  factory UserModel.fromMap(Map) {
    return UserModel(
      uid: Map['userId'],
      Username: Map['Username'],
      email: Map['email'],
      photoUrl: Map['photoUrl'],
    );
  }

you're referring to the Map as it type, so it throws the error. you need to referr to a Map object, not the Map type, so try this :

    // receving data from the server
  factory UserModel.fromMap(Map data) {
    return UserModel(
      uid: data['userId'],
      Username: data['Username'],
      email: data['email'],
      photoUrl: data['photoUrl'],
    );
  }

CodePudding user response:

while feting the data you need to declare the response as Map<String, dynamic>? even after doing that also if the error remains, try adding Map['userId].toString() || Map['userId] as String. refer below code

      final favoriteResponse = await http.get(url);
  final favoriteData =
      json.decode(favoriteResponse.body) as Map<String, dynamic>?;
  final List<Product> loadedProducts = [];
  extractedData?.forEach((prodId, prodData) {
    loadedProducts.add(Product(
        id: prodId,
        title: prodData['title'],
        description: prodData['description'],
        price: prodData['price'],
        imageUrl: prodData['imageUrl'],
        isFavorite:
            favoriteData == null ? false : favoriteData[prodId] ?? false));
  });
  _items = loadedProducts;
  notifyListeners();
} 

CodePudding user response:

Don't use Map as variable name, it is a DataType

  factory UserModel.fromMap(map) {
    return UserModel(
      uid: map['userId'],
      Username: map['Username'],
      email: map['email'],
      photoUrl: map['photoUrl'],
    );
  }

CodePudding user response:

Make sure

userId

is a String in your firestore

  • Related