我想在我的flatter应用程序中显示来自登录API的登录响应json数据的通知计数

我想在我的flatter应用程序中显示来自登录API的登录响应json数据的通知计数,api,flutter,http,authentication,Api,Flutter,Http,Authentication,我已经成功地从登录api登录,然后我从这里得到了json响应。从响应中,我可以获取一些数据。但是无法获取通知数组,需要计算通知数组的通知图标计数。我怎么做?请帮忙。 响应json格式为- { "id": 1, "name": "Mr Admin", "email": "admin2@gmail.com", "username": "ad

我已经成功地从登录api登录,然后我从这里得到了json响应。从响应中,我可以获取一些数据。但是无法获取通知数组,需要计算通知数组的通知图标计数。我怎么做?请帮忙。 响应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、姓名、电子邮件等,但无法访问未读通知。 我的代码- 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;
  }
}
class LoginResponseModel{
最终字符串标记;
最终字符串错误;
LoginResponseModel({this.token,this.error});
factory LoginResponseModel.fromJson(映射json){
返回LoginResponseModel(
令牌:json[“令牌”]!=null?json[“令牌”]:“”,
错误:json[“错误”]!=null?json[“错误”]:“”,
);
}
}
类LoginRequestModel{
字符串电子邮件;
字符串密码;
字符串用户名;
LoginRequestModel({
这是一封电子邮件,
这个密码,
这个.username,
});
映射到JSON(){
地图={
//“email”:email.trim(),
“用户名”:username.trim(),
“密码”:password.trim(),
};
返回图;
}
}
登录模型

  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;
  }
}
class LoginResponseModel{
最终字符串标记;
最终字符串错误;
LoginResponseModel({this.token,this.error});
factory LoginResponseModel.fromJson(映射json){
返回LoginResponseModel(
令牌:json[“令牌”]!=null?json[“令牌”]:“”,
错误:json[“错误”]!=null?json[“错误”]:“”,
);
}
}
类LoginRequestModel{
字符串电子邮件;
字符串密码;
字符串用户名;
LoginRequestModel({
这是一封电子邮件,
这个密码,
这个.username,
});
映射到JSON(){
地图={
//“email”:email.trim(),
“用户名”:username.trim(),
“密码”:password.trim(),
};
返回图;
}
}
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 = "my Url";




    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: (){

          },
                ),
              ],
            ),
          ),
        ),
      ),
      ),
    );
  }
}
导入“包装:颤振/材料.省道”;
进口“包装:颤振/cupertino.dart”;
进口“包装:颤振/材料.省道”;
导入“package:shared_preferences/shared_preferences.dart”;
将“package:http/http.dart”导入为http;
导入“dart:convert”;
导入“homepage.dart”;
类登录扩展StatefulWidget{
@凌驾
_LoginState createState()=>\u LoginState();
}
类_LoginState扩展了状态{
var-allData;
TextEditingController _userController=TextEditingController();
TextEditingController_passwordController=TextEditingController();
bool_isLoading=false;
//api登录的排列方法
签名(字符串用户名、字符串密码)异步{
String url=“我的url”;
SharedReferences SharedReferences=等待SharedReferences.getInstance();
映射体={“用户名”:用户名,“密码”:密码
};
var通知;
var-jsonResponse;
var res=await http.post(url,body:body);
//需要检查api状态
如果(res.statusCode==200){
jsonResponse=json.decode(res.body);
notification=jsonResponse['unread_notifications'];
打印(“响应状态:${res.statusCode}”);
打印(“响应状态:${res.body}”);
if(jsonResponse!=null){
设置状态(){
_isLoading=false;
});
setString(“token”,jsonResponse['token']);
Navigator.of(context).pushandremoveintil(
MaterialPageRoute(生成器:(BuildContext)=>
主页(
电子邮件:jsonResponse['email'],
名称:jsonResponse['name'],
用户名:jsonResponse['username'],
通知:通知,
),
),
(路由)=>false);
}
}否则{
设置状态(){
_isLoading==false;
});
打印(“响应状态:${res.body}”);
}
}
@凌驾
小部件构建(构建上下文){
返回材料PP(
家:脚手架(
正文:SingleChildScrollView(
儿童:中心(
子:容器(
填充:来自LTRB(20,100,20,20)的边缘设置,
子:列(
mainAxisAlignment:mainAxisAlignment.center,
crossAxisAlignment:crossAxisAlignment.center,
儿童:[
文本(“登录”,
样式:TextStyle(字体大小:32),
),
大小盒子(
身高:30,
),
卡片(
形状:圆形矩形边框(
边界半径:边界半径。圆形(20),
),
子:容器(
身高:220,
宽度:MediaQuery.of(context).size.width,
装饰:盒子装饰(
边界半径:边界半径。圆形(20),
),
子:列(
儿童:[
填充物(
填充:常量边集。全部(30),
孩子:TextField(
控制器:_userController,
装饰:输入装饰(hintText:“用户名”),
),
),
填充物(
填充:常量边集。全部(30),
孩子:TextField(
控制器:_passwordController,
蒙昧文字:对,
装饰:输入装饰(hintText:“密码”),
),
),
],
),
),
),
大小盒子(
身高:60,
宽度:MediaQuery.of(context).size.width,
孩子:升起按钮(
颜色:颜色。浅蓝色,
形状:圆形矩形边框(
边界半径:边界
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"]),

        );
      }),
),

          ],
        ),
      ),
    );
  }
}