settings_page.dart使用evenetbus监听退出的操作,清空用户的相关信息,然后刷新界面的信息
import 'package:flutter/material.dart';
import 'package:flutterapp2/common/event_bus.dart';
import 'package:flutterapp2/constants/Constants.dart';
import 'package:flutterapp2/utils/data_utils.dart';
/**
* 左侧抽屉 settings
*/
class SettingsPage extends StatefulWidget {
@override
_SettingsPageState createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,//阴影
title: Text(
'settings',
style: TextStyle(color: Color(AppColors.APPBAR)),
),
iconTheme: IconThemeData(
color: Color(AppColors.APPBAR),
),
),
//按钮
body: Center(
child: FlatButton(
onPressed: () {
//退出登录
DataUtils.clearLoginInfo().then((_) {
eventBus.fire(LogoutEvent());
Navigator.of(context).pop();
});
},
child: Text(
'Login Out',
style: TextStyle(fontSize: 25.0),
)),
),
);
}
}
profile_page.dart
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterapp2/common/event_bus.dart';
import 'package:flutterapp2/constants/Constants.dart';
import 'package:flutterapp2/utils/data_utils.dart';
import 'package:flutterapp2/utils/net_utils.dart';
import 'login_web_page.dart';
/**
* 主界面My
*/
class ProfilePage extends StatefulWidget {
@override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
List menuTitles = [
'我的消息',
'阅读记录',
'我的博客',
'我的问答',
'我的活动',
'我的团队',
'邀请好友',
];
List menuIcons = [
Icons.message,
Icons.print,
Icons.error,
Icons.phone,
Icons.send,
Icons.people,
Icons.person,
];
String userAvatar;
String userName;
@override
void initState() {
// TODO: implement initState
super.initState();
//尝试显示用户信息
_showUerInfo();
eventBus.on<LoginEvent>().listen((event) {
//获取用户信息并显示
_getUerInfo();
});
eventBus.on<LogoutEvent>().listen((event) {
//登出需要刷新用户信息
_showUerInfo();
});
}
_getUerInfo() {
DataUtils.getAccessToken().then((accessToken){
if (accessToken == null || accessToken.length == 0) {
return;
}
Map<String, dynamic> params = Map<String, dynamic>();
params['access_token'] = accessToken;
params['dataType'] = 'json';
print('Debug accessToken: $accessToken');
NetUtils.get(AppUrls.OPENAPI_USER, params).then((data) {
//{"gender":"male","name":"Damon2019","location":"湖南 长沙","id":2006874,"avatar":"https://oscimg.oschina.net/oscnet/up-21zvuaor7bbvi8h2a4g93iv9vve2wrnz.jpg!/both/50x50?t=1554975223000","email":"3262663349@qq.com","url":"https://my.oschina.net/damon007"}
//data: {"gender":"male","name":"Augfun","location":"广东 深圳","id":4571926,"avatar":"https://static.oschina.net/uploads/user/2285/4571926_50.jpg?t=1593452705000","email":"1234556@outlook.com","url":"https://my.oschina.net/u/4571926"}
print('Debug data: $data');
//解析数据
Map<String, dynamic> map = json.decode(data);
if (mounted) {
setState(() {
userAvatar = map['avatar'];
userName = map['name'];
});
}
DataUtils.saveUserInfo(map);
});
});
}
_showUerInfo() {
//userName信息和头像信息更新
DataUtils.getUserInfo().then((user) {
if (mounted) {
setState(() {
if (user != null) {
userAvatar = user.avatar;
userName = user.name;
} else {
userAvatar = null;
userName = null;
}
});
}
});
}
@override
Widget build(BuildContext context) {
return ListView.separated(
itemBuilder: (context, index) {
//My界面的头部
if(index == 0){
//头像用Container装起来
return _buildHeader();
}
index -= 1;
return ListTile(
leading: Icon(menuIcons[index]),
title: Text(menuTitles[index]),
trailing: Icon(Icons.arrow_forward_ios),//尾巴
onTap: () {
_login();
},
);
},
//分割线
separatorBuilder: (context, index) {
return Divider();
},
itemCount: menuTitles.length + 1
);
}
_login() async {
final result = await Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => LoginWebPage()));
if (result != null && result == 'refresh') {
print('Debug profile page LoginEvent');
//登录成功
eventBus.fire(LoginEvent());
}
}
Container _buildHeader() {
return Container(
height: 150.0,
color: Color(AppColors.APP_THEME),
//头像的布局填充
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
//先判断网路图片是否为空
child: userAvatar != null
? Container(
width: 60.0,
height: 60.0,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Color(0xffffffff),
width: 2.0,
),
image: DecorationImage(
//加载网路图片
image: NetworkImage(userAvatar),
fit: BoxFit.cover,
),
),
)
//加载网路图片
: Image.asset('assets/images/ic_avatar_default.png',
width: 60.0,
height: 60.0,
),
onTap: () {
//执行登录
_login();
},
),
SizedBox(
),
Text(
userName ??= '点击头像登录',
style: TextStyle(color: Color(0xffffffff)),
),
],
),
),
);
}
}
data_utils.dart
import 'package:flutterapp2/models/user.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DataUtils{
static const String SP_ACCESS_TOKEN = 'access_token';
static const String SP_REFRESH_TOKEN = 'refresh_token';
static const String SP_UID = 'uid';
static const String SP_TOKEN_TYPE = 'token_type';
static const String SP_EXPIRES_IN = 'expires_in';
static const String SP_IS_LOGIN = 'is_login';
//用户信息字段
static const String SP_USER_GENDER = 'gender';
static const String SP_USER_NAME = 'name';
static const String SP_USER_LOCATION = 'location';
static const String SP_USER_ID = 'id';
static const String SP_USER_AVATAR = 'avatar';
static const String SP_USER_EMAIL = 'email';
static const String SP_USER_URL = 'url';
//存储数据
// {"access_token":"aa105aaf-ca4f-4458-822d-1ae6a1fa33f9","refresh_token":"daae8b80-3ca6-4514-a8ae-acb3a82c951c","uid":2006874,"token_type":"bearer","expires_in":510070}
static Future<void> saveLoginInfo(Map<String, dynamic> map) async {
if (map != null && map.isNotEmpty) {
SharedPreferences sp = await SharedPreferences.getInstance();
sp
..setString(SP_ACCESS_TOKEN, map[SP_ACCESS_TOKEN])
..setString(SP_REFRESH_TOKEN, map[SP_REFRESH_TOKEN])
..setInt(SP_UID, map[SP_UID])
..setString(SP_TOKEN_TYPE, map[SP_TOKEN_TYPE])
..setInt(SP_EXPIRES_IN, map[SP_EXPIRES_IN])
..setBool(SP_IS_LOGIN, true);
}
}
//清楚登陆数据
static Future<void> clearLoginInfo() async {
SharedPreferences sp = await SharedPreferences.getInstance();
sp
..setString(SP_ACCESS_TOKEN, '')
..setString(SP_REFRESH_TOKEN, '')
..setInt(SP_UID, -1)
..setString(SP_TOKEN_TYPE, '')
..setInt(SP_EXPIRES_IN, -1)
..setBool(SP_IS_LOGIN, false);
}
//是否登录
static Future<bool> isLogin() async {
SharedPreferences sp = await SharedPreferences.getInstance();
bool isLogin = sp.getBool(SP_IS_LOGIN);
return isLogin != null && isLogin;
}
//获取token
static Future<String> getAccessToken() async {
SharedPreferences sp = await SharedPreferences.getInstance();
return sp.getString(SP_ACCESS_TOKEN);
}
//{"gender":"male","name":"Damon2019","location":"湖南 长沙","id":2006874,"avatar":"https://oscimg.oschina.net/oscnet/up-21zvuaor7bbvi8h2a4g93iv9vve2wrnz.jpg!/both/50x50?t=1554975223000","email":"3262663349@qq.com","url":"https://my.oschina.net/damon007"}
//data: {"gender":"male","name":"Augfun","location":"广东 深圳","id":4571926,"avatar":"https://static.oschina.net/uploads/user/2285/4571926_50.jpg?t=1593452705000","email":"123456@outlook.com","url":"https://my.oschina.net/u/4571926"}
//保存用户的信息
static saveUserInfo(Map<String, dynamic> map) async {
if (map != null && map.isNotEmpty) {
SharedPreferences sp = await SharedPreferences.getInstance();
String gender = map[SP_USER_GENDER];
String name = map[SP_USER_NAME];
String location = map[SP_USER_LOCATION];
int id = map[SP_USER_ID];
String avatar = map[SP_USER_AVATAR];
String email = map[SP_USER_EMAIL];
String url = map[SP_USER_URL];
sp
..setString(SP_USER_GENDER, gender)
..setString(SP_USER_NAME, name)
..setString(SP_USER_LOCATION, location)
..setInt(SP_USER_ID, id)
..setString(SP_USER_AVATAR, avatar)
..setString(SP_USER_EMAIL, email)
..setString(SP_USER_URL, url);
User user = new User(
id: id,
name: name,
gender: gender,
avatar: avatar,
email: email,
location: location,
url: url);
return user;
}
return null;
}
//获取用户信息
static Future<User> getUserInfo() async {
SharedPreferences sp = await SharedPreferences.getInstance();
bool isLogin = sp.getBool(SP_IS_LOGIN);
if (isLogin == null || !isLogin) {
return null;
}
User user = new User();
user.gender = sp.getString(SP_USER_GENDER);
user.name = sp.getString(SP_USER_NAME);
user.location = sp.getString(SP_USER_LOCATION);
user.id = sp.getInt(SP_USER_ID);
user.avatar = sp.getString(SP_USER_AVATAR);
user.email = sp.getString(SP_USER_EMAIL);
user.url = sp.getString(SP_USER_URL);
return user;
}
}
效果图如下: