如何使用dio在flutter中成功响应时导航到不同的屏幕

如何解决如何使用dio在flutter中成功响应时导航到不同的屏幕

我正在尝试使用 dio 在成功响应后导航到其他屏幕。但是我遇到了错误,并且在登录时仍然堆栈。

我仍然从颤振开始。

这是我的登录页面

import 'dart:ui';
import 'package:app/utils/api_provider.dart';
import 'package:flutter_signin_button/button_list.dart';
import 'package:flutter_signin_button/button_view.dart';
import 'package:app/utils/Strings.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:app/screens/signupscreen.dart';

import 'home_screen.dart';

class Loginscreen extends StatefulWidget {
  @override
  _LoginscreenState createState() => _LoginscreenState();
}

class _LoginscreenState extends State<Loginscreen> {
  String loginUrl = Africapital.login_url;
  String msgError = "";

  TextEditingController _usernameee = new TextEditingController();
  TextEditingController _password = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,body: SingleChildScrollView(
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colors.white,Colors.white],begin: Alignment.bottomLeft,end: Alignment.topLeft),),child: Center(
            child: Column(
              children: <Widget>[
                SizedBox(
                  height: 50,new Container(
                  alignment: Alignment.center,height: 100,width: 100,margin: EdgeInsets.only(
                    left: 40.0,decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(100),color: Colors.white60,boxShadow: [
                      BoxShadow(color: Colors.white60,spreadRadius: 5),],image: DecorationImage(
                      image: AssetImage('assets/images/44.jpg'),fit: BoxFit.contain,SizedBox(
                  height: 15,Center(
                  child: Text(msgError,style: TextStyle(
                          color: Colors.red,fontWeight: FontWeight.bold,fontSize: 20)),SizedBox(
                  height: 5,Container(
                  alignment: Alignment(-0.90,0.90),margin: const EdgeInsets.only(left: 20.0,right: 20.0),child: Text(
                    'Sign in with your account',style: TextStyle(
                        color: Colors.black54,fontSize: 16,fontWeight: FontWeight.w500),SizedBox(
                  height: 20.0,Container(
                  alignment: Alignment.center,padding: const EdgeInsets.only(left: 1,right: 1),child: TextField(
                    controller: _usernameee,cursorColor: Colors.indigoAccent,style: TextStyle(color: Color(0xFF1a60be)),decoration: new InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(vertical: 5.0),labelText: '      Email',focusedBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(color: Color(0xFF1a60be),width: 2.0),enabledBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(color: Colors.black38,width: 1.0),hintText: '      email@email.com',hintStyle: TextStyle(
                          fontSize: 15,letterSpacing: 1.5,color: Color(0xFF1a60be),fontWeight: FontWeight.w900),filled: true,hoverColor: Colors.black,focusColor: Colors.transparent,fillColor: Colors.white.withOpacity(0.3),border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.white38),borderRadius: BorderRadius.circular(10),SizedBox(
                  height: 20,child: TextField(
                    controller: _password,obscureText: true,decoration: new InputDecoration(
                      labelText: '      Password',contentPadding: const EdgeInsets.symmetric(vertical: 5.0),hintText: '    ••••••••',hintStyle: TextStyle(
                          fontSize: 25,letterSpacing: 2.5,Row(
                  mainAxisAlignment: MainAxisAlignment.end,children: <Widget>[
                    GestureDetector(
                      onTap: () {},child: Container(
                        child: Text(
                          'Forgot Password?',style: TextStyle(
                              color: Colors.black,fontWeight: FontWeight.w700),SizedBox(
                      width: 40,)
                  ],Padding(
                  padding: const EdgeInsets.only(left: 25,right: 25),child: ButtonTheme(
                      buttonColor: Color(0xFF3fc99c),minWidth: MediaQuery.of(context).size.width,height: 45,child: RaisedButton(
                        onPressed: () {
                          _doLogin(context);
                        },child: Text(
                          'Continue',style: TextStyle(color: Colors.white,fontSize: 22),shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(5)),)),Align(
                  alignment: Alignment(-0.80,child: Text(
                    'Or Continue with',fontWeight: FontWeight.w800),Container(
                  width: MediaQuery.of(context).size.width,margin: const EdgeInsets.only(left: 25,child: SignInButton(
                    Buttons.Google,onPressed: () {},child: SignInButton(
                    Buttons.Facebook,SizedBox(
                  height: 25,Row(
                  mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
                    Text(
                      "Don't Have an Account?",style: TextStyle(
                          color: Colors.black87,fontSize: 14,fontWeight: FontWeight.w400),SizedBox(
                      width: 10,GestureDetector(
                      onTap: () {
                        Navigator.push(context,MaterialPageRoute(builder: (ctx) => Signscreen()));
                      },child: Text(
                        'Sign up',style: TextStyle(
                          decoration: TextDecoration.underline,fontWeight: FontWeight.w800,fontSize: 18,color: Colors.black,SizedBox(
                      height: 40,)
              ],);
  }

  void _doLogin(BuildContext context) async {
    String usernameee = _usernameee.text;
    String password = _password.text;
    ApiProvider apiService = new ApiProvider();
    print("hello");
    final loginresponse =
        await apiService.getLogin(uname: usernameee,passcode: password);
    if (loginresponse.response.data != 200) {
      throw Exception("error");
    } else {
      navigateToSubPage(context);
    }
  }

  Future navigateToSubPage(context) async {
    Navigator.push(
        context,MaterialPageRoute(builder: (context) => HomeScreen()));
  }
}

这是我的 api_provider.dart

import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter_session/flutter_session.dart';

class ApiProvider {
  Dio _dio;
  String aToken = '';

  final BaseOptions options = new BaseOptions(
    baseUrl: 'https://sooo.co.ke/africanapp/',connectTimeout: 15000,receiveTimeout: 13000,);
  static final ApiProvider _instance = ApiProvider._internal();

  factory ApiProvider() => _instance;

  ApiProvider._internal() {
    _dio = Dio(options);
    _dio.interceptors
        .add(InterceptorsWrapper(onRequest: (Options options) async {
      // to prevent other request enter this interceptor.
      _dio.interceptors.requestLock.lock();
      // We use a new Dio(to avoid dead lock) instance to request token.
      //Set the cookie to headers
      options.headers["cookie"] = aToken;

      _dio.interceptors.requestLock.unlock();
      return options; //continue
    }));
  }

  // ignore: missing_return
  Future<LoginApiResponse> getLogin({String passcode,String uname}) async {
    final request = {"email": uname,"password": passcode};

    FormData formData = FormData.fromMap({
      'email': uname,'password': passcode,});

    print(request);

    try {
      final response = await _dio.post('/',data: formData);
      //getting cookies from response
      String jsonsDataString = response.data.toString();
      final jsonData = jsonDecode(jsonsDataString);

      final cookies = response.headers.map['set-cookie'];
      print(cookies);
      print(response.data);
      var message = jsonData['msg'];
      var usrid = jsonData['uid'];
      var name = jsonData['username'];
      var mail = jsonData['email'];
      var images = jsonData['profile'];

      if (message == "welcomeback") {
        await FlutterSession().set('username',usrid);
        await FlutterSession().set('username',name);
        await FlutterSession().set('email',mail);
        await FlutterSession().set('image',images);
        print(message + " dan status : " + message);
      }

      //print(response.headers.toString());
      if (response.statusCode == 200) {
        final authToken = cookies[1].split(';')[0]; // server sending cookie
        // authToken in local storage,pass5. in further api calls.
        aToken =
            authToken; // global variable to refresh current api calls to add cookie.
        print(authToken);
      } else {
        // If that response was not OK,throw an error.
        throw Exception('Failed to load post');
      }
      return LoginApiResponse(jsonData);
    } catch (e) {
      print('Error: $e');
    }

    
  }

}

class LoginApiResponse {
  final Response response;
  LoginApiResponse(this.response);
}

谁能检查一下并告诉我我的问题出在哪里。提前致谢。

我真的很需要这个帮助,我很想尽快完成我的项目。

请帮忙。

解决方法

final jsonData = jsonDecode(jsonsDataString);
...
return LoginApiResponse(jsonData);
...
if (loginresponse.response.data != 200) 

解码后jsonData只有数据部分,没有statusCode,所以在_doLogin()loginresponse中你不会有状态部分,因此您不会导航到其他页面。

,

好的,我知道你想在这里实现什么。 所以基本上你想在响应成功时导航到另一个屏幕。 所以,你的情况如下:

<tr *ngFor="let tenant of lstTenants | search:searchTerm:hasFinanacialDebt:hasntFinanacialDebt">
    <td>{{tenant.name}}</td>
    <td>{{tenant.phoneNumber}}</td>
    <td>{{tenant.address}}</td>
    <td>{{tenant.financialDebt}}</td>
</tr>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-