這篇將會完成資料接入的部分,我們使用的資料庫是 firebase 的 realtime database ,還沒使用過或是不太了解的可以參考前面的文章。
資料結構
User 類別
class User {
String id ;
int money = 0 ;
String lastUse = "" ;
String online = "" ;
String name = "" ;
String pic = "" ;
User(this.id) ;
User.fromDataSnapshot(DataSnapshot dataSnapshot){
Map<String, dynamic> json = Map<String, dynamic>.from(dataSnapshot.value);
id = dataSnapshot.key ;
money = json['money'];
name = json['name'];
pic = json['pic'] ;
lastUse = json['lastUse'] ;
online = json['online'] ;
}
User.fromJson(String id ,Map<String ,dynamic> json){
money = json['money'];
name = json['name'];
pic = json['pic'] ;
lastUse = json['lastUse'] ;
online = json['online'] ;
}
Map<String, dynamic> toJson(){
return {
"money" : money ,
"name" : name,
"pic" : pic,
"lastUse" : lastUse,
"online" : online
};
}
}
在網路層讀取資料
//in WebService.dart
Future<List<User>> getUserList() async{
List<User> users = [] ;
DataSnapshot datasnap = await _database.reference().child("users").once() ;
Map<String, dynamic> data = Map<String, dynamic>.from(datasnap.value) ;
data.forEach((key, value) {
Map<String, dynamic> dataValue = Map<String, dynamic>.from(value) ;
User user = User.fromJson(key ,dataValue) ;
users.add(user) ;
});
return users ;
}
取得 user 資料
// in UserListPageState.dart
List<User> users = [] ;
getData() async {
WebService().getUserList().then((list) => {
setState((){users = list;})
});
}
@override
void initState() {
getData() ;
super.initState();
}
照片設定
Widget getImageView(int index){
if(users[index].pic == null){
if (users[index].name == null){
return CircleAvatar(child: Text(""),) ;
}else{
return CircleAvatar(child: Text(users[index].name),) ;
}
}else{
return CircleAvatar(backgroundImage: NetworkImage(users[index].pic),);
}
}
ListView設定
final listBuilder = ListView.builder(
itemCount: users.length,
itemBuilder: (context,index){
return ListTile(
leading: getImageView(index),
title: Text("${users[index].name}"),
subtitle: Text("Last Use : ${users[index].lastUse}"),
);
},
);
這部分是真實的資料
圖片的部分怕有隱私的問題我就沒顯示了