36 Flutter仿京东商城项目 用户登录 退出登录 事件广播更新状态
Login.dart
import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_jdshop/config/Config.dart'; import 'package:flutter_jdshop/pages/tabs/Tabs.dart'; import 'package:flutter_jdshop/services/ScreenAdapter.dart'; import 'package:flutter_jdshop/services/Storage.dart'; import 'package:flutter_jdshop/widget/JdButton.dart'; import 'package:fluttertoast/fluttertoast.dart'; import '../widget/JdText.dart'; import '../widget/JdText.dart'; import '../services/EventBus.dart'; class LoginPage extends StatefulWidget { LoginPage({Key key}) : super(key: key); _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { //监听登录页面销毁的事件: dispose(){ super.dispose(); eventBus.fire(new UserEvent("登录成功...")); } String username = ""; String password = ''; doLogin() async { RegExp reg = new RegExp(r"^1\d{10}$"); if (!reg.hasMatch(this.username)) { Fluttertoast.showToast( msg: "手机号格式不正确", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER); } else if (password.length < 6) { Fluttertoast.showToast( msg: "密码不正确", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER); } else { var api = "${Config.domain}api/doLogin"; var response = await Dio().post(api, data: {"username": this.username, "password": this.password}); if (response.data["success"]) { print(response); //保存信息, Storage.setString('userInfo',json.encode(response.data["userinfo"])); Navigator.pop(context); } else { Fluttertoast.showToast( msg: "${response.data["message"]}", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER, ); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: IconButton( icon: Icon(Icons.close), onPressed: () { Navigator.pop(context); }, ), title: Text('登录页面'), actions: <Widget>[ FlatButton( child: Text('客服'), onPressed: () {}, ) ], ), body: Container( padding: EdgeInsets.all(ScreenAdapter.width(20)), child: ListView( children: <Widget>[ Center( child: Container( margin: EdgeInsets.only(top: 30), height: ScreenAdapter.width(160), width: ScreenAdapter.width(160), child: Image.asset('images/login.png',fit: BoxFit.cover), // child: Image.network( // 'https://www.iting.com/images/flutter/list5.jpg'), ), ), JdText( text: "请输入用户名", onChanged: (value) { print(value); this.username = value; }, ), SizedBox(height: 20), JdText( text: "请输入密码", password: true, onChanged: (value) { print(value); this.password = value; }, ), SizedBox(height: 20), Container( padding: EdgeInsets.all(ScreenAdapter.width(20)), child: Stack( children: <Widget>[ Align( alignment: Alignment.centerLeft, child: Text("忘记密码"), ), Align( alignment: Alignment.centerRight, child: InkWell( onTap: () { Navigator.pushNamed(context, '/RegisterFirst'); }, child: Text("新用户注册"), ), ) ], ), ), SizedBox(height: 20), JdButton( text: "登录", color: Colors.red, cb: doLogin, ) ], ), ), ); } }
User.dart
import 'package:flutter/material.dart'; import 'package:flutter_jdshop/services/ScreenAdapter.dart'; import 'package:flutter_jdshop/services/Storage.dart'; import 'package:flutter_jdshop/services/UserServices.dart'; import 'package:flutter_jdshop/widget/JdButton.dart'; import '../../services/EventBus.dart'; class UserPage extends StatefulWidget { UserPage({Key key}) : super(key: key); _UserPageState createState() => _UserPageState(); } class _UserPageState extends State<UserPage> { bool isLogin = false; List userInfo = []; @override void initState() { // TODO: implement initState super.initState(); this._getUserinfo(); //监听登录页面改变的事件: eventBus.on<UserEvent>().listen((event) { print(event.str); this._getUserinfo(); }); } _getUserinfo() async { var isLogin = await UserServices.getUserLoginState(); var userInfo = await UserServices.getUserInfo(); print(userInfo); print(isLogin); setState(() { this.userInfo = userInfo; this.isLogin = isLogin; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("用户中心"), ), body: ListView( children: <Widget>[ Container( height: ScreenAdapter.height(220), width: double.infinity, decoration: BoxDecoration( image: DecorationImage( image: AssetImage('images/user_bg.jpg'), fit: BoxFit.cover)), child: Row( children: <Widget>[ Container( margin: EdgeInsets.fromLTRB(10, 0, 10, 0), child: ClipOval( child: Image.asset( 'images/user.png', fit: BoxFit.cover, width: ScreenAdapter.width(100), height: ScreenAdapter.width(100), ), ), ), !this.isLogin ? Expanded( flex: 1, child: InkWell( onTap: () { Navigator.pushNamed(context, '/login'); }, child: Text('登录/注册', style: TextStyle(color: Colors.white)), ), ) : Expanded( flex: 1, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("用户名:${this.userInfo[0]["username"]}", style: TextStyle( color: Colors.white, fontSize: ScreenAdapter.size(32))), Text("普通会员", style: TextStyle( color: Colors.white, fontSize: ScreenAdapter.size(32))) ], ), ), ], ), ), ListTile( leading: Icon(Icons.home, color: Colors.red), title: Text('首页')), Divider(), ListTile(leading: Icon(Icons.home), title: Text('首页')), ListTile(leading: Icon(Icons.home), title: Text('首页')), ListTile(leading: Icon(Icons.home), title: Text('首页')), this.isLogin ? Container( padding: EdgeInsets.all(20), child: JdButton( color: Colors.red, text: "退出登录", cb: () { UserServices.loginOut(); this._getUserinfo(); }, ), ) : Text("") ], ), ); } }
EventBus.dart
import 'package:event_bus/event_bus.dart'; //Bus 初始化 EventBus eventBus = EventBus(); //商品详情广播数据: class ProductContentEvent{ String str; ProductContentEvent(String str){ this.str=str; } } //用户中心广播: class UserEvent{ String str; UserEvent(String str){ this.str=str; } }
UserServices.dart
import 'dart:convert'; import '../services/Storage.dart'; class UserServices { static getUserInfo() async { List userinfo; try { List userInfoData = json.decode(await Storage.getString("userInfo")); userinfo = userInfoData; } catch (e) { userinfo = []; } return userinfo; } static getUserLoginState() async{ var userInfo =await UserServices.getUserInfo(); if (userInfo.length > 0 && userInfo[0]['username'] != "") { return true; } return false; } static loginOut() { Storage.remove("userInfo"); } }
RegisterThird.dart
import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_jdshop/config/Config.dart'; import 'package:flutter_jdshop/widget/JdButton.dart'; import 'package:flutter_jdshop/widget/JdText.dart'; import 'package:fluttertoast/fluttertoast.dart'; import '../services/Storage.dart'; //引入Tabs: import '../pages/tabs/Tabs.dart'; class RegisterThirdPage extends StatefulWidget { Map arguments; RegisterThirdPage({Key key, this.arguments}) : super(key: key); _RegisterThirdPageState createState() => _RegisterThirdPageState(); } class _RegisterThirdPageState extends State<RegisterThirdPage> { String tel; String code; String password=''; String rpassword=''; @override void initState() { // TODO: implement initState super.initState(); this.tel = widget.arguments["tel"]; this.code = widget.arguments["code"]; } //注册: doRegister() async { if (password.length < 6) { Fluttertoast.showToast( msg: "密码长度不能小于6位", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER, ); } else if (password != rpassword) { Fluttertoast.showToast( msg: "密码和确认密码不一致", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER, ); }else{ var api = '${Config.domain}api/register'; var responses = await Dio().post(api, data: { "tel": this.tel, "code": this.code, "password": this.password }); if (responses.data["success"]) { //保存信息, Storage.setString('userInfo',json.encode(responses.data['userinfo']) ); //返回到根: Navigator.of(context).pushAndRemoveUntil( new MaterialPageRoute(builder: (context)=>new Tabs()), (route)=>route==null); } else { Fluttertoast.showToast( msg: "${responses.data["message"]}", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER, ); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('用户注册-第三步'), ), body: Container( padding: EdgeInsets.all(20), child: ListView( children: <Widget>[ SizedBox(height: 10), JdText( text: "请输入密码", password: true, onChanged: (value) { this.password=value; print(value); }, ), SizedBox(height: 10), JdText( text: "请输入确认密码", password: true, onChanged: (value) { this.rpassword=value; print(value); }, ), SizedBox(height: 10), JdButton( text: "注册", color: Colors.red, cb: doRegister, ) ], ), ), ); } } //