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

Need to save my login api json response in SharedPreferences

我已经从 Api 登录。然后我得到了json的响应数据。我需要在 sharedpreferences 中保存 id 、name 和 api_token 。我该怎么做。我已经显示了所有代码。请帮忙。 响应 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",
            "type": "App\Notifications\HandSlipStatusNotification",
            "notifiable_id": 1,
            "notifiable_type": "App\User",
            "data": {
                "payment_id": 471,
                "generate_payment_id": "10200471",
                "message": "Hand Slip Disbursed.",
                "amount": 850
            },
            "read_at": null,
            "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, 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.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,
                  width: MediaQuery.of(context).size.width,
                  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.username, 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然后添加下面的class,你可以添加更多的功能

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,
                  width: MediaQuery.of(context).size.width,
                  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);
            });
          }