In typescript
//user is coming from firebase Users collection
let userData = user.data() as {name:string, age:int}
What will be the alternatives of above code in dart?
CodePudding user response:
Json
like data type in dart is Map
but it's handy to code.
The most efficient way is using Json Serialization
.
Use a User
model, and parse json
to it,
User userData = User.fromJson(user.data());
You can generate Model class directly from Json
automatically from here.
So no pain in the neck.
User model
class will be like this:
import 'dart:convert';
User userFromJson(String str) => User.fromJson(json.decode(str));
String userToJson(User data) => json.encode(data.toJson());
class User {
User({
this.name,
this.age,
});
String name;
int age;
User copyWith({
String name,
int age,
}) =>
User(
name: name ?? this.name,
age: age ?? this.age,
);
factory User.fromJson(Map<String, dynamic> json) => User(
name: json["name"],
age: json["age"],
);
Map<String, dynamic> toJson() => {
"name": name,
"age": age,
};
}
Happy coding TT
CodePudding user response:
This is how we can handle the data if it is coming from FireBase.
class MessageStreams extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: _fireStore.collection('messages').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.lightBlue,
),
);
}
final messages = snapshot.data.docs.reversed;
List<MessageBubble> messageBubbles = [];
for (var message in messages) {
final messageText = message['text'];
final messageSender = message['sender'];
print(loggedInUser);
print(loggedInUser.email);
final currentUser = loggedInUser.email;
if (currentUser == messageSender) {}
final messageBubble = MessageBubble(
messageSender, messageText, currentUser == messageSender);
messageBubbles.add(messageBubble);
}
return Expanded(
child: ListView(
reverse: true,
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
children: messageBubbles,
),
);
},
);
}
}