需要将我的登录api json响应保存在SharedPreferences中

如何解决需要将我的登录api json响应保存在SharedPreferences中

我已经从登录Api登录。然后我得到了json的响应数据。我需要将id,名称和api_token保存在sharedpreferences中。我该怎么做。我已经显示了所有代码。请帮忙。 响应json格式为-

{
    "id": 1,"name": "Mr Admin","email": "admin2@gmail.com","username": "admin2","api_token": "oYfajebhRzlxpMZV8dHI6w5R8CrpgybaGqX2ZaIXkGpumE9hZSgLVVINAgaF","user_types_id": null,"created_at": "2020-01-21 16:21:48","updated_at": "2020-10-14 11:31:10","deleted_at": null,"unread_notifications": [
        {
            "id": "d54ee0cc-054a-4d51-a53b-5f6f658841ae","type": "App\\Notifications\\HandSlipStatusNotification","notifiable_id": 1,"notifiable_type": "App\\User","data": {
                "payment_id": 471,"generate_payment_id": "10200471","message": "Hand Slip Settled.","amount": 850
            },"read_at": null,"created_at": "2020-10-12 15:50:38","updated_at": "2020-10-12 15:50:38"
        },{
            "id": "aedb7880-4201-4805-b017-62242dfed741","message": "Hand Slip Disbursed.","created_at": "2020-10-12 15:50:25","updated_at": "2020-10-12 15:50:25"
        },

我可以显示id,name,email等,但是无法访问unread_notifications。 我的代码- api_service.dart->

 class LoginResponseModel {
  final String token;
  final String error;
  LoginResponseModel({this.token,this.error});
  factory LoginResponseModel.fromJson(Map<String,dynamic> json) {
    return LoginResponseModel(
      token: json["token"] != null ? json["token"] : "",error: json["error"] != null ? json["error"] : "",);
  }
}
class LoginRequestModel {
  String email;
  String password;
  String username;

  LoginRequestModel({
    this.email,this.password,this.username,});

  Map<String,dynamic> toJson() {
    Map<String,dynamic> map = {
      // 'email': email.trim(),'username': username.trim(),'password': password.trim(),};

    return map;
  }
}

login_model

  class LoginResponseModel {
  final String token;
  final String error;

  LoginResponseModel({this.token,this.error});

  factory LoginResponseModel.fromJson(Map<String,);
  }
}

class LoginRequestModel {
  String email;
  String password;
  String username;

  LoginRequestModel({
    this.email,};

    return map;
  }
}

login.dart

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'homepage.dart';


class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  var allData ;

  TextEditingController _userController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();


  bool _isLoading = false;


  // arrange method for api log in

  signIn( String username,String password) async {
    // String url = "https://reqres.in/api/login";
    String url = "myurl";




    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    Map body = { "username": username,"password": password
    };
    var notificatiion;
    var jsonResponse;
    var res = await http.post(url,body: body);

    //need to check the api status

    if (res.statusCode == 200) {
      jsonResponse = json.decode(res.body);
      notificatiion = jsonResponse['unread_notifications'];
      print("Response status: ${res.statusCode}");
      print("Response status: ${res.body}");


      if (jsonResponse != null) {
        setState(() {
          _isLoading = false;
        });

        sharedPreferences.setString("token",jsonResponse['token']);
        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (BuildContext) =>
                HomePage(
                email: jsonResponse['email'],name: jsonResponse['name'],username : jsonResponse['username'],notification: notificatiion,),(Route<dynamic> route) => false);
      }
    } else {
      setState(() {
        _isLoading == false;
      });
      print(" Response status : ${res.body}");


    }
  }




  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
      body:  SingleChildScrollView(
        child: Center(
          child: Container(
            padding: EdgeInsets.fromLTRB(20,100,20,20),child: Column(
              mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: [

                Text("Login",style: TextStyle(fontSize: 32),SizedBox(
                  height: 30,Card(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),child: Container(
                    height: 220,width: MediaQuery.of(context).size.width,decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),child: Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(30),child: TextField(
                            controller: _userController,decoration: InputDecoration(hintText: "username"),Padding(
                          padding: const EdgeInsets.all(30),child: TextField(
                            controller: _passwordController,obscureText: true,decoration: InputDecoration(hintText: "Password"),],SizedBox(
                  height: 60,child: RaisedButton(
                    color: Colors.lightBlue,shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16),child: Text("Sign In"),onPressed: _userController.text == ""||
                        _passwordController.text == ""
                        ? null
                        : () {
                      setState(() {
                        _isLoading = true ;

                      });
                      signIn(_userController.text,_passwordController.text);
                    },SizedBox(
                  height: 20,FlatButton(
                  child: Text("Forgot password"),onPressed: (){

          },);
  }
}

我想在主页上显示所有响应值。在通知的图标中,我想显示数组计数。 homepage.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'login.dart';
import 'login.dart';

class HomePage extends StatelessWidget {
  String email;
  String name;
  String username;
   List<dynamic> notification;

  HomePage({this.email,this.name,this.notification,});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Cash-Management"),backgroundColor: Colors.blue,actions: [
            IconButton(icon: Icon(Icons.notifications),onPressed: () {}),IconButton(
                icon: Icon(Icons.exit_to_app),onPressed: () {
                  Navigator.push(
                    context,MaterialPageRoute(builder: (context) => Login()),);
                }),body: ListView(
          children: <Widget>[
            Container(
              height: 200,child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,children: <Widget>[
                  Text(
                    "  $email ",style: TextStyle(fontSize: 16),Text(" $name "),Text(" $username "),Container(
  height: 300,child:   ListView.builder(
      itemCount: notification == null ?  0 : notification.length,itemBuilder: (context,index){
        return ListTile(
          title: Text(notification[index] ["id"]),subtitle: Text(notification[index]["type"]),);
      }),);
  }
}

解决方法

请参考该模型以访问unread_notifications

Data itemModelFromJson(Map<String,dynamic> data) => Data.fromJson(data);

class Data {
  Data({
    this.items,});

  List<Item> items;

  factory Data.fromJson(Map<String,dynamic> json) => Data(
        items: List<Item>.from(json['unread_notifications'].map((x) => Item.fromJson(x))),);
}

class Item {
  Item({
    this.itemType,this.itemCreated,});

  String itemType;
  String itemCreated;

  factory Item.fromJson(Map<String,dynamic> json) => Item(
        itemType: json["type"],itemCreated: json["created_at"],);
}
,

您无需在此处使用模型,我对登录代码进行了一些更改,可以粘贴整个登录代码

创建一个文件SharedPrefrence.dart,然后在其中添加以下类,您可以添加更多功能

import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

class SharedPrefrence {
  Future<bool> setToken(String token) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString("token",token);
  }

  Future<String> getToken() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString("token") ?? '';
  }

  Future<bool> setUserId(String userId) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString("user_id",userId);
  }

  Future<String> getUserId() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString("user_id") ?? '';
  }

  Future<bool> setName(String name) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString("name",name);
  }

  Future<String> getName() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString("name") ?? '';
  }

  Future<bool> setLoggedIn(bool status) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setBool("logged_in",status);
  }

  Future<bool> getLogedIn() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool("logged_in") ?? false;
  }
}

Login.dart

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import 'SharedPrefrence.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  bool isprocesscomplete = false;
  TextEditingController _userController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  String BaseUrl = "http://www.accounting.emicrodev.com/api/login";
 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,body: SingleChildScrollView(
        child: Center(
          child: Container(
            padding: EdgeInsets.fromLTRB(20,100,20,20),child: Column(
              mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: [
                Text(
                  "Login",style: TextStyle(fontSize: 32),),SizedBox(
                  height: 30,Card(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),child: Container(
                    height: 220,width: MediaQuery.of(context).size.width,decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),child: Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(30),child: TextField(
                            controller: _userController,decoration: InputDecoration(hintText: "username"),Padding(
                          padding: const EdgeInsets.all(30),child: TextField(
                            controller: _passwordController,obscureText: true,decoration: InputDecoration(hintText: "Password"),],SizedBox(
                  height: 60,child: RaisedButton(
                    color: Colors.lightBlue,onPressed: () {
                      if (_userController.text == "" ||
                          _passwordController.text == "") {
                        final snackBar = SnackBar(
                            content: Text("Enter Username and Password"));
                        _scaffoldKey.currentState.showSnackBar(snackBar);
                      } else {
                        signIn(_userController.text,_passwordController.text);
                      }
                    },child: ProgressButton(),shape: RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(16),SizedBox(
                  height: 20,FlatButton(
                  child: Text("Forgot password"),onPressed: () {},);
  }

  Widget ProgressButton() {
    if (isprocesscomplete != false) {
      return CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white));
    } else {
      return new Text(
        "Sign In",style: const TextStyle(
          color: Colors.white,fontSize: 15.0,);
    }
  }

  void signIn(String username,String password) async {
    setState(() {
      isprocesscomplete = true;
    });
    var response = await http.post(BaseUrl,headers: {"Content-Type": "application/json"},body: json.encode({
          "username": username,"password": password,}));

    Map<String,dynamic> value = json.decode(response.body);
    // print('Respone ${response.body}');
    if (response.statusCode == 200) {
      try {
        ///You don't need it but it will be cool for show progress dialgo for 4 second then redirect even if we get reslut
        Future.delayed(Duration(seconds: 4),() {
          // 5s over make it false
          setState(() {
            isprocesscomplete = false;
          });
        });

        Map<String,dynamic> value = json.decode(response.body);
        print('Respone ${response.body}');
        SharedPrefrence().setToken(value['api_token'].toString());
        SharedPrefrence().setName(value['name']);
        SharedPrefrence().setUserId(value['id'].toString());

        ///This is used when user loged in you can set this true,///next time you open you need to check loginc in main.dart or splashscreen if this is true if it is true then
        ///redirect to home page it is false then redirect to Login page
        ///When you logout the app make sure you set this as false like "SharedPrefrence().setLoggedIn(false);"
        SharedPrefrence().setLoggedIn(true);

        ///Redirect to Home page
        // Navigator.pushAndRemoveUntil(
        //                         context,//                         MaterialPageRoute(
        //                             builder: (context) => HomePage()),//                         ModalRoute.withName("/login"));

      } catch (e) {
        e.toString();
        final snackBar =
            SnackBar(content: Text("something wrong,Try again ?"));
        _scaffoldKey.currentState.showSnackBar(snackBar);
      }
    } else {
      var message = value['error'];
      final snackBar = SnackBar(
          backgroundColor: Colors.redAccent[700],content: Text(message.toString()));
      _scaffoldKey.currentState.showSnackBar(snackBar);
    }
  }
}**

您可以像这样访问主页中的“保存的共享偏好”值

     String nametoprint;
      String tokentoprint;
        
          @override
          void initState() {
            super.initState();
            Future name = SharedPrefrence().getName();
            name.then((data) async {
              nametoprint = data;
              print(nametoprint);
            });

           Future token= SharedPrefrence().getToken();
            token.then((data) async {
              tokentoprint= data;
              print(tokentoprint);
            });
          }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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-