颤动问题:如何从登录导航到主页

问题描述 投票:0回答:1

当我单击登录时,每次对话框中都会显示错误

但是在我的调试控制台中我显示登录成功

我不明白为什么登录没有发生,它一次又一次地抛出捕获错误 虽然我在 deb 控制台登录成功

登录后应该进入主页。

这是我的auth.dart

import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:rest_api_login/utils/api.dart';
import 'package:http/http.dart' as http;
import 'package:rest_api_login/utils/http_exception.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Auth with ChangeNotifier {
  var MainUrl = Api.authUrl;
  var AuthKey = Api.authKey;

  // String _token;
  String _uid;
  String _username;
  DateTime _expiryDate;
  Timer _authTimer;

  bool get isAuth {
    return token != null;
  }

  String get token {
    if (_expiryDate != null &&
        _expiryDate.isAfter(DateTime.now()) &&
        _uid != null) {
      return _uid;
    }
  }

  String get uid {
    return _uid;
  }

  String get username {
    return _username;
  }

  Future<void> logout() async {
    _username = null;
    _uid = null;
    _expiryDate = null;

    if (_authTimer != null) {
      _authTimer.cancel();
      _authTimer = null;
    }

    notifyListeners();

    final pref = await SharedPreferences.getInstance();
    pref.clear();
  }

  void _autologout() {
    if (_authTimer != null) {
      _authTimer.cancel();
    }
    final timetoExpiry = _expiryDate.difference(DateTime.now()).inSeconds;
    _authTimer = Timer(Duration(seconds: timetoExpiry), logout);
  }

  Future<bool> tryautoLogin() async {
    final pref = await SharedPreferences.getInstance();
    if (!pref.containsKey('userData')) {
      return false;
    }

    final extractedUserData =
        json.decode(pref.getString('userData')) as Map<String, Object>;

    final expiryDate = DateTime.parse(extractedUserData['expiryDate']);
    if (expiryDate.isBefore(DateTime.now())) {
      return false;
    }

    _uid = extractedUserData['uid'];
    _username = extractedUserData['username'];
    _expiryDate = expiryDate;
    notifyListeners();
    _autologout();

    return true;
  }

  Future<void> Authentication(
      String username, String password, String endpoint) async {
    try {
      var url = Uri.parse('$MainUrl&action=$endpoint');

      final responce = await http.post(url,
          body: ({
            'username': username,
            'password': password,
          }));

      final responceData = json.decode(responce.body);
      print(responceData);
      if (responceData['error'] != null) {
        throw HttpException(responceData['error']['msg']);
      }

      _uid = responceData['uid'];
      _username = responceData['username'];
      _expiryDate = DateTime.now()
          .add(Duration(seconds: int.parse(responceData['expiresIn'])));

      _autologout();
      notifyListeners();

      final prefs = await SharedPreferences.getInstance();
      final userData = json.encode({
        'uid': _uid,
        'username': _username,
        'expiryDate': _expiryDate.toIso8601String(),
      });

      prefs.setString('userData', userData);

      print('check' + userData.toString());
    } catch (e) {
      throw e;
    }
  }

  Future<void> login(String username, String password) {
    return Authentication(username, password, 'login');
  }

  Future<void> signUp(String username, String password) {
    return Authentication(username, password, 'registration');
  }
}

这是我的login.dart页面

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:rest_api_login/providers/auth.dart';
import 'package:rest_api_login/screens/home_Screen.dart';
import 'package:rest_api_login/screens/signup_screen.dart';
import 'package:rest_api_login/utils/http_exception.dart';

class LoginScreen extends StatefulWidget {
  static const String routeName = "/login";

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey();

  Map<String, String> _authData = {'username': '', 'password': ''};

  Future _submit() async {
    if (!_formKey.currentState.validate()) {
      //invalid
      return;
    }
    _formKey.currentState.save();
    try {
      await Provider.of<Auth>(context, listen: false)
          .login(_authData['username'], _authData['password']);
    } on HttpException catch (e) {
      var errorMessage = 'Authentication Failed';
      if (e.toString().contains('INVALID_EMAIL')) {
        errorMessage = 'Invalid email';
        _showerrorDialog(errorMessage);
      } else if (e.toString().contains('EMAIL_NOT_FOUND')) {
        errorMessage = 'This email not found';
        _showerrorDialog(errorMessage);
      } else if (e.toString().contains('INVALID_PASSWORD')) {
        errorMessage = 'Invalid Password';
        _showerrorDialog(errorMessage);
      }
    } catch (error) {
      var errorMessage = 'Plaese try again later';
      _showerrorDialog(errorMessage);
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      // backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Container(
          child: Stack(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).size.height * 0.65,
                width: MediaQuery.of(context).size.width * 0.85,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        topRight: Radius.circular(360),
                        bottomRight: Radius.circular(360)),
                    color: Colors.blue),
              ),
              Container(
                padding:
                    EdgeInsets.only(top: 50, left: 20, right: 20, bottom: 50),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "Sign In",
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 40),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      "Sign in with your username or email",
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 10),
                    ),
                    Form(
                      key: _formKey,
                      child: Container(
                        padding: EdgeInsets.only(top: 50, left: 20, right: 20),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "Username or Email",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            TextFormField(
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  prefixIcon: Icon(
                                    Icons.person,
                                    color: Colors.white,
                                  )),
                              // validator: (value) {
                              //   if (value.isEmpty || !value.contains('@')) {
                              //     return 'Invalid email';
                              //   }
                              // },
                              onSaved: (value) {
                                _authData['username'] = value;
                              },
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              "Password",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            TextFormField(
                              obscureText: true,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  prefixIcon: Icon(
                                    Icons.vpn_key,
                                    color: Colors.white,
                                  )),
                              validator: (value) {
                                if (value.isEmpty || value.length < 5) {
                                  return 'Password is to Short';
                                }
                              },
                              onSaved: (value) {
                                _authData['password'] = value;
                              },
                            ),
                            Container(
                              padding: EdgeInsets.only(top: 40),
                              width: 140,
                              child: RaisedButton(
                                  onPressed: () {
                                    _submit();
                                  },
                                  shape: RoundedRectangleBorder(
                                    borderRadius:
                                        new BorderRadius.circular(10.0),
                                  ),
                                  child: Text(
                                    'Sign In',
                                    style: TextStyle(color: Colors.white),
                                  ),
                                  color: Colors.green),
                            ),
                            Align(
                              alignment: Alignment.bottomRight,
                              child: InkWell(
                                onTap: () {
                                  Navigator.of(context).push(MaterialPageRoute(
                                      builder: (ctx) => SignUpScreen()));
                                },
                                child: Container(
                                  padding: EdgeInsets.only(top: 90),
                                  child: Text(
                                    "Create Account",
                                    style: TextStyle(
                                        decoration: TextDecoration.underline,
                                        color: Colors.blue,
                                        fontSize: 16),
                                  ),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _showerrorDialog(String message) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text(
          'An Error Occurs',
          style: TextStyle(color: Colors.blue),
        ),
        content: Text(message),
        actions: <Widget>[
          FlatButton(
            child: Text('Okay'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          )
        ],
      ),
    );
  }
}

这是我的 main.dart 页面

import 'package:flutter/material.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Providers/signup_auth.dart';
import 'package:login_and_signup/Screens/home_screen.dart';
import 'package:login_and_signup/Screens/login.dart';
import 'package:login_and_signup/Screens/splash_screen.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: Auth(),

      child: Consumer<Auth>(
        builder: (context, auth, _) => MaterialApp(
          title: 'Flutter demo',
          theme: ThemeData(
              primarySwatch: Colors.blue,
              visualDensity: VisualDensity.adaptivePlatformDensity),
          //home: LoginScreen(),
          home: auth.isAuth!
              ? HomeScreen()
              : FutureBuilder(
                  future: auth.tryautoLogin(),
                  builder: (context, snapshot) =>
                      snapshot.connectionState == ConnectionState.waiting
                          ? SplashScreen()
                          : LoginScreen()),
        ),
      ),
      
    );
  }
}


这是我的主页.dart 页面

import 'package:flutter/material.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Screens/login.dart';
// import 'package:login_signup_with_api/Providers/auth.dart';
import 'package:provider/provider.dart';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: Center(
          
          child: RaisedButton(
        onPressed: () {
          Navigator.of(context).pushReplacementNamed('/');
          Provider.of<Auth>(context, listen: false).logout();
        },
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        child: Text('logout'),
        color: Colors.green,
      )
          // color: Colors.green,
          // ),
          ),
    );
  }
}

flutter dart flutter-layout flutter-dependencies flutter-test
1个回答
0
投票
  1. 登录屏幕中的错误处理:

    尝试{ 等待Provider.of(上下文,听:假) .login(_authData['用户名'], _authData['密码']); } on HttpException catch (e) { _showerrorDialog(e.toString()); } 捕获(错误){ _showerrorDialog('发生意外错误。'); }

  2. 登录成功后导航:

    尝试{ 等待Provider.of(上下文,听:假) .login(_authData['用户名'], _authData['密码']); Navigator.of(context).pushReplacementNamed(HomeScreen.routeName); } on HttpException catch (e) { _showerrorDialog(e.toString()); } 捕获(错误){ _showerrorDialog('发生意外错误。'); }

  3. 调试:

    未来的认证( 字符串用户名、字符串密码、字符串端点) async { 尝试 { var url = Uri.parse('$MainUrl&action=$endpoint'); 最终响应=等待http.post(url, body: { '用户名':用户名, '密码':密码, }); 最终responceData = json.decode(responce.body); print('身份验证响应:$responceData'); // ...其余代码 } 捕获 (e) { print('身份验证错误:$e'); 扔 e; } }

    Future _submit() 异步 { // ...现有代码 尝试 { 等待Provider.of(上下文,听:假) .login(_authData['用户名'], _authData['密码']); print('登录成功'); Navigator.of(context).pushReplacementNamed(HomeScreen.routeName); } on HttpException catch (e) { print('登录错误:$e'); _showerrorDialog(e.toString()); } 捕获(错误){ print('登录意外错误:$error'); _showerrorDialog('发生意外错误。'); } }

© www.soinside.com 2019 - 2024. All rights reserved.