身份验证成功后重定向用户 - Flutter

时间:2021-05-29 19:07:56

标签: json api flutter dart authentication

我正在尝试在身份验证成功后将用户重定向到应用主屏幕。在我的代码中,我尝试通过 future 类处理用户流,但我没有成功。

用户存储库

import 'dart:convert';
import 'package:flutter_session/flutter_session.dart';
import 'package:http/http.dart' as http;

//Authenication: confirms if password and mail matches with server.
Future<UserInfo> authenticate(String email, String password) async {
  final response = await http.post(
    Uri.parse('api url'),       //Makes the post request
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{                                    //Input values from the form given to the json of the request.
      'email': email,
      'password': password,
    })
  );

  UserInfo id = UserInfo.fromJson(jsonDecode(response.body));             //Call the function that creates the class with the output of the json
                          
  if (response.statusCode == 200) {
    return UserInfo.fromJson(jsonDecode(response.body));
  } 
  else if (response.statusCode == 200) {
    await FlutterSession().set('id', id);                                 //Saves the id to the session variables
  }
  else {
    throw Exception('Error');
  }
}

class UserInfo {
    
  final int id;

  UserInfo({this.id});

  factory UserInfo.fromJson(Map<String, dynamic> json) {                  //Parses through the response´s json and creates a class with that value
    return UserInfo(
      id: json['id_usuario'] as int,
    );
  }
}

在这里,我发出一个 http post 请求并创建一个包含一些 json 实例的类作为回报。我还将实例 id 存储到 flutter_session 插件中,以便以后查询用户名等。

登录页面

import 'package:flutter/material.dart';
import 'package:treelife_flutter/user/repository/user_repository.dart';
import 'package:treelife_flutter/user/ui/screens/sign_in_screen.dart';
import 'package:treelife_flutter/user/ui/widgets/background.dart';
import 'package:treelife_flutter/widgets/button_back.dart';
import 'package:treelife_flutter/widgets/button_green.dart';
import 'package:treelife_flutter/widgets/text_input.dart';

import '../../../tree_life_cupertino.dart';


class LogInScreen extends StatefulWidget {

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

class _LogInScreenState extends State<LogInScreen> {

  final _loginFormKey = GlobalKey<FormState>();
  final _mailController = TextEditingController();
  final _passwordController = TextEditingController();
  Future<UserInfo> _futureUserInfo;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        resizeToAvoidBottomInset: false,                                 // Avoid overfloww when keyboard shows
        body: Stack(     
          children: [
            Background(
              height: null,
              color: Colors.white,
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Column(
                  children: [
                    Row(
                      children: [
                        ButtonBack(
                          onPressed: () {
                            Navigator.push(
                              context, 
                              MaterialPageRoute(builder: (context) => SignInScreen() )
                            );
                          },
                        )
                      ],
                    ),
                    Row(                                                 // Título    
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Padding(
                          padding: const EdgeInsets.fromLTRB(30, 30, 30, 0),
                          child: Text(
                            "Ingresa",
                            style:  Theme.of(context).textTheme.headline1,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                SizedBox(
                  height: 200,
                  width: double.infinity,
                  child: Padding(
                    padding: const EdgeInsets.only(bottom: 40, top: 40),
                    child: Image.asset('assets/icons/logo_treelife.png'),
                  ),
                ),
                Form(
                  key: _loginFormKey,
                  child: Expanded(
                    child: Column(
                      children: [
                        Container(                                        
                          width: double.infinity,
                          child: Padding(
                            padding: const EdgeInsets.fromLTRB(30, 0, 30, 30),
                            child: TextInput(
                              controller: _mailController,
                              hint: 'Email',
                              suffixIcon:'assets/icons/at.png'
                            ),
                          ),
                        ),
                        Container(                                         //  Primer campo registro: contraseña
                          width: double.infinity,
                          child: Padding(
                            padding: const EdgeInsets.fromLTRB(30, 0, 30, 30),
                            child: TextInput(
                              controller: _passwordController,
                              hint: 'Contraseña',
                              suffixIcon:'assets/icons/password.png'
                            ),
                          ),
                        ),
                        ButtonGreen(                                             // Botón Registro
                          marginTop: 30,
                          marginLeft: 30,
                          marginRight: 30,
                          marginBottom: 30,
                          text: "¡Plantemos árboles!",
                          fontColor: Colors.white,
                          fontSize: 20,
                          onPressed: () {
                            setState(() {
                              _futureUserInfo = authenticate(_mailController.text, _passwordController.text);
                            });
                          },
                          width: double.infinity,
                          height: 50,
                          boxColor: Color(0xFFD2E1BD),
                        ),
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 40),
                  child: Image.asset('assets/sign_in/login_illustration.png'),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
  FutureBuilder<UserInfo> buildFutureBuilder() {
    return FutureBuilder<UserInfo>(
      future: _futureUserInfo,
      builder: (context, snapshot){
        if (snapshot.hasData) {
          Navigator.push(
            context, 
            MaterialPageRoute(builder: (context) => TreelifeCupertino()));
        } else if (snapshot.hasError) {
          return Text('${snapshot.error}');
        }
        return CircularProgressIndicator();
      }
    );
  }
}

在这里,我遵循了 flutter send data to the internet 文档,在那里我尝试通过 buildfuture 函数应用来逻辑,但如果身份验证成功,我添加了 navigate.of(context) 以进行重定向.

0 个答案:

没有答案