Flutter出现NoSuchMethodError:Type类无[]实例方法求助
解决NoSuchMethodError: Class 'Type' has no instance method '[]'错误
问题根源
这个错误由两处代码问题导致:
- 模型类的工厂方法错误使用类型名
Map作为参数名,导致访问字段时实际调用的是Map类型的方法而非实例方法 - 页面中调用模型方法时,错误传入
Map类型而非Firestore返回的实际数据快照
修复步骤
1. 修正user_model代码
// 遵循Dart命名规范,类名使用大驼峰 class Usermodel { final String? uid; final String? email; final String? username; final String? photoUrl; Usermodel({this.uid, this.email, this.username, this.photoUrl}); // 工厂方法参数指定类型并使用合法变量名 factory Usermodel.fromMap(Map<String, dynamic> map) { return Usermodel( uid: map['userId'], // 使用参数变量名map,而非类型名Map username: map['Username'], email: map['email'], photoUrl: map['photoUrl'], ); } }
2. 修正Profile页面代码
buildProfileHeader() { // 方法名遵循小驼峰规范 return FutureBuilder( future: userRef.doc(widget.userProfile).get(), builder: (context, snapshot) { if (!snapshot.hasData) { return const CircularProgressIndicator(); // 修正组件名称 } // 获取Firestore文档的实际数据Map final userData = snapshot.data!.data() as Map<String, dynamic>; // 将实际数据传入模型方法 Usermodel user = Usermodel.fromMap(userData); return Padding( padding: const EdgeInsets.all(16.0), child: Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CircleAvatar( radius: 40.0, backgroundColor: Colors.grey, backgroundImage: CachedNetworkImageProvider(user.photoUrl!), ), ], ), Container( alignment: Alignment.center, padding: const EdgeInsets.all(12.0), child: Text( user.username as String, style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 16.0, ), ), ), ], ), ); }, ); }
内容的提问来源于stack exchange,提问作者Abderrezak Douba
相关产品推荐
相关产品推荐

