添加 github Oauth ,个人中心

This commit is contained in:
yifeng.yl
2019-05-30 20:04:01 +08:00
parent dbcdbab7d2
commit 617e2953b3
13 changed files with 294 additions and 91 deletions

BIN
assets/images/arrow.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@ -1,5 +1,5 @@
class Api{ class Api{
static const String BASE_URL = 'http://30.10.29.190:6001/'; static const String BASE_URL = 'http://30.10.25.17:6001/';
// static const String BASE_URL = 'http://flutter-go.alibaba.net/'; // static const String BASE_URL = 'http://flutter-go.alibaba.net/';
static const String DO_LOGIN = BASE_URL+'doLogin';//登陆 static const String DO_LOGIN = BASE_URL+'doLogin';//登陆

View File

@ -11,6 +11,7 @@ import 'package:flutter_go/model/search_history.dart';
import 'package:flutter_go/utils/analytics.dart' as Analytics; import 'package:flutter_go/utils/analytics.dart' as Analytics;
import 'package:flutter_go/views/login_page/login_page.dart'; import 'package:flutter_go/views/login_page/login_page.dart';
import 'package:flutter_go/utils/data_utils.dart'; import 'package:flutter_go/utils/data_utils.dart';
import 'package:flutter_go/model/user_info.dart';
//import 'views/welcome_page/index.dart'; //import 'views/welcome_page/index.dart';
@ -34,18 +35,27 @@ class MyApp extends StatefulWidget {
class _MyAppState extends State<MyApp> { class _MyAppState extends State<MyApp> {
bool _hasLogin = false; bool _hasLogin = false;
bool _isLoading = true; bool _isLoading = true;
UserInformation _userInfo;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
DataUtils.checkLogin().then((hasLogin) { DataUtils.checkLogin().then((hasLogin) {
if (hasLogin.runtimeType == UserInformation) {
setState(() {
_hasLogin = true;
_isLoading = false;
_userInfo = hasLogin;
});
} else {
setState(() { setState(() {
_hasLogin = hasLogin; _hasLogin = hasLogin;
_isLoading = false; _isLoading = false;
}); });
}).catchError((onError){ }
}).catchError((onError) {
setState(() { setState(() {
_hasLogin = true; _hasLogin = false;
_isLoading = false; _isLoading = false;
}); });
print('身份信息验证失败:$onError'); print('身份信息验证失败:$onError');
@ -63,7 +73,7 @@ class _MyAppState extends State<MyApp> {
} else { } else {
// 判断是否已经登录 // 判断是否已经登录
if (_hasLogin) { if (_hasLogin) {
return AppPage(); return AppPage(_userInfo);
} else { } else {
return LoginPage(); return LoginPage();
} }

View File

@ -1,24 +1,25 @@
class UserInfo { class UserInformation {
String username; String username;
int id; int id;
String avatarPic; String avatarPic;
String themeColor; String themeColor;
String urlName;
UserInfo({ UserInformation({
this.avatarPic, this.avatarPic,
this.id, this.id,
this.themeColor, this.themeColor,
this.urlName,
this.username, this.username,
}); });
factory UserInfo.fromJson(Map<String, dynamic> json) { factory UserInformation.fromJson(Map<String, dynamic> json) {
return UserInfo( String name = json['name'];
if(json['name'] == null){
name = json['url_name'];
}
return UserInformation(
avatarPic: json['avatar_pic'], avatarPic: json['avatar_pic'],
id: int.parse(json['id']), id: int.parse(json['id']),
username: json['name'], username: name,
themeColor: json['theme_color'], themeColor: json['theme_color']);
urlName: json['url_name']);
} }
} }

View File

@ -7,11 +7,12 @@ import 'package:flutter_go/components/full_screen_code_dialog.dart';
import 'package:flutter_go/views/web_page/web_view_page.dart'; import 'package:flutter_go/views/web_page/web_view_page.dart';
import 'package:flutter_go/views/home.dart'; import 'package:flutter_go/views/home.dart';
import 'package:flutter_go/views/login_page/login_page.dart'; import 'package:flutter_go/views/login_page/login_page.dart';
import 'package:flutter_go/model/user_info.dart';
// app的首页 // app的首页
var homeHandler = new Handler( var homeHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) { handlerFunc: (BuildContext context, Map<String, List<String>> params) {
return new AppPage(); return new AppPage(UserInformation(id: 0));
}, },
); );

View File

@ -8,30 +8,39 @@ class DataUtils {
// 登陆获取用户信息 // 登陆获取用户信息
static Future doLogin(Map<String, String> params) async { static Future doLogin(Map<String, String> params) async {
var response = await NetUtils.post(Api.DO_LOGIN, params); var response = await NetUtils.post(Api.DO_LOGIN, params);
print(response);
try { try {
UserInfo userInfo = UserInfo.fromJson(response['data']); UserInformation userInfo = UserInformation.fromJson(response['data']);
return userInfo; return userInfo;
} catch (err) { } catch (err) {
return response['data']; return response['message'];
} }
} }
// 获取用户信息 // 获取用户信息
static Future<UserInfo> getUserInfo(Map<String, String> params) async { static Future<UserInformation> getUserInfo(Map<String, String> params) async {
var response = await NetUtils.get(Api.GET_USER_INFO, params); var response = await NetUtils.get(Api.GET_USER_INFO, params);
print(response); try {
UserInfo userInfo = UserInfo.fromJson(response['data']); UserInformation userInfo = UserInformation.fromJson(response['data']);
return userInfo; return userInfo;
} catch (err) {
return response['message'];
}
} }
// 验证登陆 // 验证登陆
static Future checkLogin() async {
static Future<bool> checkLogin() async {
var response = await NetUtils.get(Api.CHECK_LOGIN); var response = await NetUtils.get(Api.CHECK_LOGIN);
print('验证登陆:$response'); try {
if (response['success']) {
UserInformation userInfo = UserInformation.fromJson(response['data']);
return userInfo;
} else {
return response['success']; return response['success'];
} }
} catch (err) {
return response['message'];
}
}
// 退出登陆 // 退出登陆
static Future<bool> logout() async { static Future<bool> logout() async {

View File

@ -17,12 +17,12 @@ class NetUtils {
var response; var response;
// 设置代理 便于本地 charles 抓包 // 设置代理 便于本地 charles 抓包
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(HttpClient client) { // (HttpClient client) {
client.findProxy = (uri) { // client.findProxy = (uri) {
return "PROXY 30.10.29.190:8888"; // return "PROXY 30.10.25.17:8888";
}; // };
}; // };
Directory documentsDir = await getApplicationDocumentsDirectory(); Directory documentsDir = await getApplicationDocumentsDirectory();
String documentsPath = documentsDir.path; String documentsPath = documentsDir.path;

View File

@ -0,0 +1,130 @@
import 'package:flutter/material.dart';
import 'package:flutter_go/model/user_info.dart';
import 'package:share/share.dart';
class DrawerPage extends StatefulWidget {
final UserInformation userInfo;
DrawerPage({Key key, this.userInfo}) : super(key: key);
@override
_DrawerPageState createState() => _DrawerPageState();
}
class _DrawerPageState extends State<DrawerPage> {
final TextStyle textStyle =
TextStyle(fontSize: 16, fontWeight: FontWeight.w300);
@override
Widget build(BuildContext context) {
return ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text(''),
accountEmail: Container(
padding: const EdgeInsets.only(bottom: 20.0),
child: Text(
widget.userInfo.username,
style: TextStyle(fontSize: 28),
),
),
decoration: BoxDecoration(
image: new DecorationImage(
fit: BoxFit.cover,
image: new NetworkImage(widget.userInfo.avatarPic),
),
),
),
ListTile(
leading: Icon(
Icons.search,
size: 27.0,
color: Theme.of(context).primaryColor,
),
title: Text(
'搜索',
style: textStyle,
),
onTap: () {},
),
// new Divider(),
ListTile(
leading: Icon(
Icons.favorite,
size: 27.0,
),
title: Text(
'我的收藏',
style: textStyle,
),
onTap: () {},
),
// new Divider(),
ListTile(
leading: Icon(
Icons.settings,
size: 27.0,
),
title: Text(
'更多设置',
style: textStyle,
),
onTap: () {},
),
new Divider(),
ListTile(
leading: Icon(
Icons.email,
size: 27.0,
),
title: Text(
'反馈/建议',
style: textStyle,
),
onTap: () {},
),
ListTile(
leading: Icon(
Icons.info,
size: 27.0,
),
title: Text(
'关于 App',
style: textStyle,
),
onTap: () {},
),
ListTile(
leading: Icon(
Icons.share,
size: 27.0,
),
title: Text(
'分享 App',
style: textStyle,
),
onTap: () {
Share.share('https://github.com/alibaba/flutter-go');
},
),
new Divider(),
ListTile(
leading: Icon(
Icons.exit_to_app,
size: 27.0,
),
title: Text(
'登出',
style: textStyle,
),
onTap: () {
Share.share('check out my website https://example.com');
},
),
],
);
}
}

View File

@ -1,9 +1,11 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter_go/views/first_page/drawer_page.dart';
import './first_page.dart'; import './first_page.dart';
import './sub_page.dart'; import './sub_page.dart';
import './main_app_bar.dart'; import './main_app_bar.dart';
import './search_page.dart'; import './search_page.dart';
import 'package:flutter_go/model/user_info.dart';
class _Page { class _Page {
final String labelId; final String labelId;
@ -19,6 +21,10 @@ final List<_Page> _allPages = <_Page>[
]; ];
class MainPage extends StatelessWidget { class MainPage extends StatelessWidget {
final UserInformation userInfo;
MainPage({Key key, this.userInfo}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
print("MainPagess build......"); print("MainPagess build......");
@ -29,7 +35,7 @@ class MainPage extends StatelessWidget {
leading: Container( leading: Container(
child: new ClipOval( child: new ClipOval(
child: Image.network( child: Image.network(
'https://hbimg.huabanimg.com/9bfa0fad3b1284d652d370fa0a8155e1222c62c0bf9d-YjG0Vt_fw658', userInfo.avatarPic,
scale: 15.0, scale: 15.0,
), ),
)), )),
@ -44,17 +50,8 @@ class MainPage extends StatelessWidget {
], ],
), ),
drawer: Drawer( drawer: Drawer(
child: new ListView( child: DrawerPage(
children: <Widget>[ userInfo: userInfo,
new ListTile(
title: new Text("欢迎"),
),
new Divider(),
new ListTile(
title: new Text("设置"),
trailing: new Icon(Icons.settings),
onTap: () {}),
],
), ),
), ),
body: TabBarViewLayout(), body: TabBarViewLayout(),

View File

@ -20,10 +20,16 @@ import 'package:flutter_go/widgets/index.dart';
import 'package:flutter_go/components/search_input.dart'; import 'package:flutter_go/components/search_input.dart';
import 'package:flutter_go/model/search_history.dart'; import 'package:flutter_go/model/search_history.dart';
import 'package:flutter_go/resources/widget_name_to_icon.dart'; import 'package:flutter_go/resources/widget_name_to_icon.dart';
import 'package:flutter_go/model/user_info.dart';
const int ThemeColor = 0xFFC91B3A; const int ThemeColor = 0xFFC91B3A;
class AppPage extends StatefulWidget { class AppPage extends StatefulWidget {
final UserInformation userInfo;
AppPage(this.userInfo);
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
return _MyHomePageState(); return _MyHomePageState();
@ -32,6 +38,8 @@ class AppPage extends StatefulWidget {
class _MyHomePageState extends State<AppPage> class _MyHomePageState extends State<AppPage>
with SingleTickerProviderStateMixin { with SingleTickerProviderStateMixin {
SpUtil sp; SpUtil sp;
WidgetControlModel widgetControl = new WidgetControlModel(); WidgetControlModel widgetControl = new WidgetControlModel();
SearchHistoryList searchHistoryList; SearchHistoryList searchHistoryList;
@ -62,7 +70,7 @@ class _MyHomePageState extends State<AppPage>
} }
list list
// ..add(FirstPage()) // ..add(FirstPage())
..add(MainPage()) ..add(MainPage(userInfo:widget.userInfo))
..add(WidgetPage(Provider.db)) ..add(WidgetPage(Provider.db))
..add(CollectionPage()) ..add(CollectionPage())
..add(FourthPage()); ..add(FourthPage());
@ -117,9 +125,9 @@ class _MyHomePageState extends State<AppPage>
}, (value) {}, () {}); }, (value) {}, () {});
} }
renderAppBar(BuildContext context,Widget widget,int index) { renderAppBar(BuildContext context, Widget widget, int index) {
print('renderAppBar=====>>>>>>${index}'); print('renderAppBar=====>>>>>>${index}');
if(index == 0) { if (index == 0) {
return null; return null;
} }
return AppBar(title: buildSearchInput(context)); return AppBar(title: buildSearchInput(context));
@ -128,7 +136,7 @@ class _MyHomePageState extends State<AppPage>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return new Scaffold( return new Scaffold(
appBar: renderAppBar(context,widget,_currentIndex), appBar: renderAppBar(context, widget, _currentIndex),
body: list[_currentIndex], body: list[_currentIndex],
bottomNavigationBar: BottomNavigationBar( bottomNavigationBar: BottomNavigationBar(
items: myTabs, items: myTabs,

View File

@ -11,6 +11,7 @@ import 'package:flutter_go/event/event_model.dart';
import 'package:flutter_go/model/user_info_cache.dart'; import 'package:flutter_go/model/user_info_cache.dart';
import 'package:flutter_go/routers/application.dart'; import 'package:flutter_go/routers/application.dart';
import 'package:flutter_go/routers/routers.dart'; import 'package:flutter_go/routers/routers.dart';
import 'package:flutter_go/model/user_info.dart';
class LoginPage extends StatefulWidget { class LoginPage extends StatefulWidget {
@override @override
@ -47,7 +48,6 @@ class _LoginPageState extends State<LoginPage> {
_userInfoControlModel.getAllInfo().then((list) { _userInfoControlModel.getAllInfo().then((list) {
if (list.length > 0) { if (list.length > 0) {
UserInfo _userInfo = list[0]; UserInfo _userInfo = list[0];
print('获取的数据:${_userInfo.username} ${_userInfo.password}');
setState(() { setState(() {
_userNameEditingController.text = _userInfo.username; _userNameEditingController.text = _userInfo.username;
_passwordEditingController.text = _userInfo.password; _passwordEditingController.text = _userInfo.password;
@ -62,7 +62,6 @@ class _LoginPageState extends State<LoginPage> {
ApplicationEvent.event.on<UserGithubOAuthEvent>().listen((event) { ApplicationEvent.event.on<UserGithubOAuthEvent>().listen((event) {
if (event.isSuccess == true) { if (event.isSuccess == true) {
print('请求接口');
// oAuth 认证成功 // oAuth 认证成功
setState(() { setState(() {
isLoading = true; isLoading = true;
@ -73,7 +72,7 @@ class _LoginPageState extends State<LoginPage> {
isLoading = false; isLoading = false;
}); });
Navigator.of(context).pushAndRemoveUntil( Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => AppPage()), MaterialPageRoute(builder: (context) => AppPage(result)),
(route) => route == null); (route) => route == null);
}).catchError((onError) { }).catchError((onError) {
print('获取身份信息 error:::$onError'); print('获取身份信息 error:::$onError');
@ -81,9 +80,16 @@ class _LoginPageState extends State<LoginPage> {
isLoading = false; isLoading = false;
}); });
}); });
} else {
Fluttertoast.showToast(
msg: '验证失败',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Theme.of(context).primaryColor,
textColor: Colors.white,
fontSize: 16.0);
} }
print('这是接受到的 event ${event.isSuccess} ${event.loginName}');
// _getList();
}); });
} }
@ -223,9 +229,9 @@ class _LoginPageState extends State<LoginPage> {
isLoading = true; isLoading = true;
}); });
DataUtils.doLogin({'username': username, 'password': password}) DataUtils.doLogin({'username': username, 'password': password})
.then((result) { .then((userResult) {
if(result.runtimeType == String){ if (userResult.runtimeType == String) {
throw result; throw userResult;
} }
setState(() { setState(() {
isLoading = false; isLoading = false;
@ -236,15 +242,15 @@ class _LoginPageState extends State<LoginPage> {
_userInfoControlModel _userInfoControlModel
.insert(UserInfo(password: password, username: username)) .insert(UserInfo(password: password, username: username))
.then((value) { .then((value) {
// print('存储成功:$value'); print('存储成功:$value');
Navigator.of(context).pushAndRemoveUntil( Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => AppPage()), MaterialPageRoute(builder: (context) => AppPage(userResult)),
(route) => route == null); (route) => route == null);
}); });
}); });
} catch (err) { } catch (err) {
Navigator.of(context).pushAndRemoveUntil( Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => AppPage()), MaterialPageRoute(builder: (context) => AppPage(userResult)),
(route) => route == null); (route) => route == null);
} }
}).catchError((errorMsg) { }).catchError((errorMsg) {
@ -258,8 +264,7 @@ class _LoginPageState extends State<LoginPage> {
timeInSecForIos: 1, timeInSecForIos: 1,
backgroundColor: Theme.of(context).primaryColor, backgroundColor: Theme.of(context).primaryColor,
textColor: Colors.white, textColor: Colors.white,
fontSize: 16.0 fontSize: 16.0);
);
}); });
} }
@ -315,11 +320,28 @@ class _LoginPageState extends State<LoginPage> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: <Widget>[ children: <Widget>[
SizedBox(height: 35.0), SizedBox(height: 35.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/images/gitHub.png',
fit: BoxFit.contain,
width: 60.0,
height: 60.0,
),
Image.asset(
'assets/images/arrow.png',
fit: BoxFit.contain,
width: 40.0,
height: 30.0,
),
Image.asset( Image.asset(
'assets/images/FlutterGo.png', 'assets/images/FlutterGo.png',
fit: BoxFit.contain, fit: BoxFit.contain,
width: 100.0, width: 60.0,
height: 100.0, height: 60.0,
),
],
), ),
buildSignInTextForm(), buildSignInTextForm(),
buildSignInButton(), buildSignInButton(),
@ -330,6 +352,9 @@ class _LoginPageState extends State<LoginPage> {
color: Colors.grey[400], color: Colors.grey[400],
margin: const EdgeInsets.only(bottom: 10.0), margin: const EdgeInsets.only(bottom: 10.0),
), ),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FlatButton( FlatButton(
child: Text( child: Text(
'Github OAuth 认证', 'Github OAuth 认证',
@ -338,11 +363,25 @@ class _LoginPageState extends State<LoginPage> {
decoration: TextDecoration.underline), decoration: TextDecoration.underline),
), ),
onPressed: () { onPressed: () {
// _launchURL('https://github.com/login/oauth/authorize?client_id=cfe4795e76382ae8a5bd&scope=user,public_repo');
Application.router.navigateTo(context, Application.router.navigateTo(context,
'${Routes.webViewPage}?title=Github&url=${Uri.encodeComponent("https://github.com/login/oauth/authorize?client_id=cfe4795e76382ae8a5bd&scope=user,public_repo")}'); '${Routes.webViewPage}?title=Github&url=${Uri.encodeComponent("https://github.com/login/oauth/authorize?client_id=cfe4795e76382ae8a5bd&scope=user,public_repo")}');
}, },
),
FlatButton(
child: Text(
'游客登录',
style: TextStyle(
color: Theme.of(context).primaryColor,
decoration: TextDecoration.underline),
),
onPressed: () {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) => AppPage(UserInformation(id: 0,avatarPic: 'https://hbimg.huabanimg.com/9bfa0fad3b1284d652d370fa0a8155e1222c62c0bf9d-YjG0Vt_fw658'))),
(route) => route == null);
},
)
],
) )
], ],
), ),

View File

@ -235,6 +235,13 @@ packages:
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "0.21.0" version: "0.21.0"
share:
dependency: "direct main"
description:
name: share
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.6.1+1"
shared_preferences: shared_preferences:
dependency: "direct main" dependency: "direct main"
description: description:

View File

@ -27,6 +27,7 @@ dependencies:
url_launcher: ^5.0.2 url_launcher: ^5.0.2
# 本地存储、收藏功能 # 本地存储、收藏功能
shared_preferences: ^0.4.3 shared_preferences: ^0.4.3
share: ^0.6.1+1
flutter_spinkit: "^3.1.0" flutter_spinkit: "^3.1.0"
path_provider: ^1.0.0 path_provider: ^1.0.0
fluttertoast: ^3.1.0 fluttertoast: ^3.1.0