如何将 Profile 对象作为参数传递给 ChatPage?
How to pass a Profile object as an argument to ChatPage?
我正在编写类似 Tinder 的应用程序,但在将创建的配置文件对象传递到 ChatPage 时遇到困难。
使用时
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => ChatPage(profile: profile),
));
弹出错误:
The argument type 'Profile (where Profile is defined in d:\Documentos\UFF\LabMoveis\flutter\V8\grupoverde20212\lib\src\models\profile.dart)' can't be assigned to the parameter type 'Profile (where Profile is defined in d:\Documentos\UFF\LabMoveis\flutter\V8\grupoverde20212\lib\src\model\profile.dart)'.dartargument_type_not_assignable
profile.dart(8, 7): Profile is defined in d:\Documentos\UFF\LabMoveis\flutter\V8\grupoverde20212\lib\src\models\profile.dart
profile.dart(1, 7): Profile is defined in d:\Documentos\UFF\LabMoveis\flutter\V8\grupoverde20212\lib\src\model\profile.dart
如果有人能帮助我,代码如下:
ChatTab
// This tab shows the matches, so the user can chat with them. Also, the map can be accessed from here.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gather/src/widgets/tabs/chat.dart';
import '../../models/profile.dart';
import '../../tools/cloudstore.dart';
import '../../tools/general.dart';
import '../miscellaneous/awaitsign.dart';
import '../miscellaneous/errorsign.dart';
import '../pages/chat.dart';
class ChatTab extends StatefulWidget {
final Profile userProfile;
const ChatTab({required this.userProfile, Key? key}) : super(key: key);
@override
_ChatTabState createState() => _ChatTabState();
}
class _ChatTabState extends State<ChatTab> {
List<Profile> profiles = <Profile>[];
ListTile _tile(Profile profile) {
return ListTile(
title: Text(profile.name,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20,
)),
// subtitle: Text(subtitle),
leading: CircleAvatar(
radius: 30, backgroundImage: NetworkImage(profile.photoUrl)),
onTap: () {
print('show chat page.');
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => ChatPage(profile: profile),
));
},
);
}
@override
Widget build(BuildContext context) {
final stream = getBonds(userId: widget.userProfile.id, bonds: ['match']);
return StreamBuilder<QuerySnapshot>(
stream: stream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
final AsyncSnapshot<QuerySnapshot> snap = snapshot;
if (snapshot.connectionState == ConnectionState.waiting) {
return const AwaitSign();
} else if (snapshot.hasError) {
return const ErrorSign();
}
if (snapshot.data!.docs.isEmpty) {
return const Center(child: Text("No matches for you."));
}
profiles.clear();
return FutureBuilder<int>(
future: getProfilesFromDocs(
docs: snapshot.data!.docs, buffer: profiles),
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.hasData) {
return Stack(children: [
ListView.separated(
padding: const EdgeInsets.all(8),
itemCount: profiles.length,
itemBuilder: (BuildContext context, int index) {
return _tile(profiles[index]);
},
separatorBuilder: (BuildContext context, int index) =>
const Divider(),
),
Positioned(
right: 10,
bottom: 10,
child: FloatingActionButton(
onPressed: () {
Navigator.pushNamed(context, '/map', arguments: {
'profile': widget.userProfile,
// 'profiles': profiles
'stream': stream,
'snapshot': snap
});
},
child: const Icon(Icons.pin_drop_outlined))
)
]);
} else if (snapshot.hasError) {
return const ErrorSign();
}
return const AwaitSign();
},
);
});
}
}
简介Class
class Profile {
String id, name, photoUrl, designation, bio;
List<String>? tags;
GeoPoint? location;
Profile(
{required this.id,
required this.name,
this.bio = 'No bio',
this.designation = 'No designation',
this.photoUrl = defaultProfilePictureUrl,
this.location,
this.tags});
factory Profile.fromJSON(Map<String, dynamic> json) {
return Profile(
id: json['id'] as String,
name: json['name'] as String,
bio: json['bio'] as String,
designation: json['designation'] as String,
tags: List.from(json['tags'] as Iterable));
}
factory Profile.fromQueryDocument(QueryDocumentSnapshot qds) {
return Profile(
id: qds.id,
name: qds['name'] as String,
bio: qds['bio'] as String,
designation: qds['designation'] as String,
tags: List.from(qds['tags'] as Iterable));
}
}
聊天页面
import 'package:cloud_firestore/cloud_firestore.dart';
// import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gather/src/model/profile.dart';
// import 'package:gather/src/widgets/miscellaneous/search.dart';
class ChatPage extends StatefulWidget {
// ignore: prefer_typing_uninitialized_variables
final Profile profile;
const ChatPage({Key? key, required this.profile}) : super(key: key);
@override
_ChatPageState createState() => _ChatPageState();
}
class _ChatPageState extends State<ChatPage> {
// final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Map<String, dynamic>? data;
final TextEditingController _messageController = TextEditingController();
final ScrollController _scrollController = ScrollController();
Future<void> callback() async {
if (_messageController.text.isNotEmpty) {
await _firestore.collection('messages').add({
'text': _messageController.text,
'from': data!['profile'].id,
});
_messageController.clear();
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
}
@override
Widget build(BuildContext context) {
data ??= ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
return Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('messages').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
List<DocumentSnapshot> docs = snapshot.data!.docs;
List<Widget> messages = docs
.map((doc) => Message(
from: doc['from'],
text: doc['text'],
me: data!['profile'].id == doc['from'],
))
.toList();
return ListView();
},
)),
Row(
children: <Widget>[
Expanded(
child: TextField(
decoration: const InputDecoration(
hintText: "Escreva sua Mensagem",
border: OutlineInputBorder(),
),
controller: _messageController,
),
),
SendButton(
text: "Send",
callback: () {},
),
],
)
],
),
),
);
}
}
class SendButton extends StatelessWidget {
final String text;
final VoidCallback callback;
const SendButton({Key? key, required this.text, required this.callback})
: super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
child: Text(text, style: const TextStyle(color: Colors.orange)),
onPressed: callback);
}
}
class Message extends StatelessWidget {
final String from, text;
// final String text;
final bool me;
const Message(
{Key? key, required this.from, required this.text, required this.me})
: super(key: key);
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment:
me ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: <Widget>[
Text(
from,
),
Material(
color: me ? Colors.teal : Colors.red,
borderRadius: BorderRadius.circular(10.0),
elevation: 6.0,
child: Container(
padding:
const EdgeInsets.symmetric(vertical: 10.0, horizontal: 15.0),
child: Text(
text,
),
),
)
],
);
}
}
您使用了 Profile
的两个不同定义。
// in ChatTab
import '../../models/profile.dart';
// in ChatPage
import 'package:gather/src/model/profile.dart';
如果这两个在同一个包中,请注意 models vs model(没有 s)
我正在编写类似 Tinder 的应用程序,但在将创建的配置文件对象传递到 ChatPage 时遇到困难。 使用时
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => ChatPage(profile: profile),
));
弹出错误:
The argument type 'Profile (where Profile is defined in d:\Documentos\UFF\LabMoveis\flutter\V8\grupoverde20212\lib\src\models\profile.dart)' can't be assigned to the parameter type 'Profile (where Profile is defined in d:\Documentos\UFF\LabMoveis\flutter\V8\grupoverde20212\lib\src\model\profile.dart)'.dartargument_type_not_assignable profile.dart(8, 7): Profile is defined in d:\Documentos\UFF\LabMoveis\flutter\V8\grupoverde20212\lib\src\models\profile.dart profile.dart(1, 7): Profile is defined in d:\Documentos\UFF\LabMoveis\flutter\V8\grupoverde20212\lib\src\model\profile.dart
如果有人能帮助我,代码如下:
ChatTab
// This tab shows the matches, so the user can chat with them. Also, the map can be accessed from here.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gather/src/widgets/tabs/chat.dart';
import '../../models/profile.dart';
import '../../tools/cloudstore.dart';
import '../../tools/general.dart';
import '../miscellaneous/awaitsign.dart';
import '../miscellaneous/errorsign.dart';
import '../pages/chat.dart';
class ChatTab extends StatefulWidget {
final Profile userProfile;
const ChatTab({required this.userProfile, Key? key}) : super(key: key);
@override
_ChatTabState createState() => _ChatTabState();
}
class _ChatTabState extends State<ChatTab> {
List<Profile> profiles = <Profile>[];
ListTile _tile(Profile profile) {
return ListTile(
title: Text(profile.name,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20,
)),
// subtitle: Text(subtitle),
leading: CircleAvatar(
radius: 30, backgroundImage: NetworkImage(profile.photoUrl)),
onTap: () {
print('show chat page.');
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => ChatPage(profile: profile),
));
},
);
}
@override
Widget build(BuildContext context) {
final stream = getBonds(userId: widget.userProfile.id, bonds: ['match']);
return StreamBuilder<QuerySnapshot>(
stream: stream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
final AsyncSnapshot<QuerySnapshot> snap = snapshot;
if (snapshot.connectionState == ConnectionState.waiting) {
return const AwaitSign();
} else if (snapshot.hasError) {
return const ErrorSign();
}
if (snapshot.data!.docs.isEmpty) {
return const Center(child: Text("No matches for you."));
}
profiles.clear();
return FutureBuilder<int>(
future: getProfilesFromDocs(
docs: snapshot.data!.docs, buffer: profiles),
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.hasData) {
return Stack(children: [
ListView.separated(
padding: const EdgeInsets.all(8),
itemCount: profiles.length,
itemBuilder: (BuildContext context, int index) {
return _tile(profiles[index]);
},
separatorBuilder: (BuildContext context, int index) =>
const Divider(),
),
Positioned(
right: 10,
bottom: 10,
child: FloatingActionButton(
onPressed: () {
Navigator.pushNamed(context, '/map', arguments: {
'profile': widget.userProfile,
// 'profiles': profiles
'stream': stream,
'snapshot': snap
});
},
child: const Icon(Icons.pin_drop_outlined))
)
]);
} else if (snapshot.hasError) {
return const ErrorSign();
}
return const AwaitSign();
},
);
});
}
}
简介Class
class Profile {
String id, name, photoUrl, designation, bio;
List<String>? tags;
GeoPoint? location;
Profile(
{required this.id,
required this.name,
this.bio = 'No bio',
this.designation = 'No designation',
this.photoUrl = defaultProfilePictureUrl,
this.location,
this.tags});
factory Profile.fromJSON(Map<String, dynamic> json) {
return Profile(
id: json['id'] as String,
name: json['name'] as String,
bio: json['bio'] as String,
designation: json['designation'] as String,
tags: List.from(json['tags'] as Iterable));
}
factory Profile.fromQueryDocument(QueryDocumentSnapshot qds) {
return Profile(
id: qds.id,
name: qds['name'] as String,
bio: qds['bio'] as String,
designation: qds['designation'] as String,
tags: List.from(qds['tags'] as Iterable));
}
}
聊天页面
import 'package:cloud_firestore/cloud_firestore.dart';
// import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gather/src/model/profile.dart';
// import 'package:gather/src/widgets/miscellaneous/search.dart';
class ChatPage extends StatefulWidget {
// ignore: prefer_typing_uninitialized_variables
final Profile profile;
const ChatPage({Key? key, required this.profile}) : super(key: key);
@override
_ChatPageState createState() => _ChatPageState();
}
class _ChatPageState extends State<ChatPage> {
// final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Map<String, dynamic>? data;
final TextEditingController _messageController = TextEditingController();
final ScrollController _scrollController = ScrollController();
Future<void> callback() async {
if (_messageController.text.isNotEmpty) {
await _firestore.collection('messages').add({
'text': _messageController.text,
'from': data!['profile'].id,
});
_messageController.clear();
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
}
@override
Widget build(BuildContext context) {
data ??= ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
return Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('messages').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
List<DocumentSnapshot> docs = snapshot.data!.docs;
List<Widget> messages = docs
.map((doc) => Message(
from: doc['from'],
text: doc['text'],
me: data!['profile'].id == doc['from'],
))
.toList();
return ListView();
},
)),
Row(
children: <Widget>[
Expanded(
child: TextField(
decoration: const InputDecoration(
hintText: "Escreva sua Mensagem",
border: OutlineInputBorder(),
),
controller: _messageController,
),
),
SendButton(
text: "Send",
callback: () {},
),
],
)
],
),
),
);
}
}
class SendButton extends StatelessWidget {
final String text;
final VoidCallback callback;
const SendButton({Key? key, required this.text, required this.callback})
: super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
child: Text(text, style: const TextStyle(color: Colors.orange)),
onPressed: callback);
}
}
class Message extends StatelessWidget {
final String from, text;
// final String text;
final bool me;
const Message(
{Key? key, required this.from, required this.text, required this.me})
: super(key: key);
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment:
me ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: <Widget>[
Text(
from,
),
Material(
color: me ? Colors.teal : Colors.red,
borderRadius: BorderRadius.circular(10.0),
elevation: 6.0,
child: Container(
padding:
const EdgeInsets.symmetric(vertical: 10.0, horizontal: 15.0),
child: Text(
text,
),
),
)
],
);
}
}
您使用了 Profile
的两个不同定义。
// in ChatTab
import '../../models/profile.dart';
// in ChatPage
import 'package:gather/src/model/profile.dart';
如果这两个在同一个包中,请注意 models vs model(没有 s)