我从一个API登录,然后得到这个响应。现在我需要在通知图标中显示数组的计数。我在主页的应用程序栏中设置。我该如何实施?
{
"user_id": 1,
"user_name": "Mr Admin",
"api_token": "6S3gRnPy55JKWyiOF7SwtYO12waZ8ozSyIHUNs2XSEcMh0DfTbpP5k51y2mL",
"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": "99b433b1-9432-44ae-a57f-fcb4ff92872f",
"type": "App\\Notifications\\HandSlipStatusNotification",
"notifiable_id": 1,
"notifiable_type": "App\\User",
"data": {
"payment_id": 471,
"generate_payment_id": "10200471",
"message": "Hand Slip Approved.",
"amount": 850
},
"read_at": null,
"created_at": "2020-10-12 15:50:08",
"updated_at": "2020-10-12 15:50:08"
},
字符串
login.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../sharePreference.dart';
import 'homepage.dart';
class Login extends StatefulWidget {
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
var notification ;
bool isprocesscomplete = false;
TextEditingController _userController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
final _scaffoldKey = GlobalKey<ScaffoldState>();
String BaseUrl = "my url";
@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);
notification = value["notifications"];
// print('Response ${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('Response ${response.body}');
SharedPrefrence().setToken(value['api_token'].toString());
SharedPrefrence().setName(value['user_name']);
SharedPrefrence().setUserId(value['user_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(
user_name: value['user_name'],
api_token: value['api_token'],
id : value['user_id'],
notification: notification,
)),
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);
}
}
}
型
homepage.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../sharePreference.dart';
import 'login.dart';
import 'login.dart';
class HomePage extends StatefulWidget {
String user_name;
final api_token;
final id ;
final List<dynamic> notification ;
// List data ;
HomePage({ this.user_name, this.api_token , this.id, this.notification });
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
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);
});
}
int counter = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Cash-Management"),
backgroundColor: Colors.blue,
actions: [
new Stack(
children: <Widget>[
new IconButton(icon: Icon(Icons.notifications), onPressed: () {
setState(() {
counter = 0;
});
}),
counter != 0 ? new Positioned(
right: 11,
top: 11,
child: new Container(
padding: EdgeInsets.all(2),
decoration: new BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(6),
),
constraints: BoxConstraints(
minWidth: 14,
minHeight: 14,
),
child: Text(
'$counter',
style: TextStyle(
color: Colors.white,
fontSize: 8,
),
textAlign: TextAlign.center,
),
),
) : new Container()
],
),
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(
"${widget.user_name}",
// " ${widget.username} ",
style: TextStyle(fontSize: 16),
),
Text(
"${widget.api_token}",
// " ${widget.username} ",
style: TextStyle(fontSize: 16),
),
Text(
"${widget.id}",
// " ${widget.username} ",
style: TextStyle(fontSize: 16),
),
Text(" ${nametoprint} "),
Text("$nametoprint"),
Text("$tokentoprint"),
],
),
),
Container(
color: Colors.blue,
height: 300,
child: ListView.builder(
itemCount: widget.notification == null ? 0 : widget.notification.length,
itemBuilder: (context, index){
return ListTile(
title: Text(widget.notification[index] ["id"]),
subtitle: Text(widget.notification[index]["type"]),
);
}),
),
],
),
floatingActionButton: FloatingActionButton(onPressed: () {
print("Increment Counter");
setState(() {
counter++;
});
}, child: Icon(Icons.add),),
),
);
}
}
型
我需要计算JSON中的数组,并需要在通知图标中显示计数。请用你的知识帮助我。
1条答案
按热度按时间7vux5j2d1#
创建一个josn类,并将数据Map到class中,通过class可以访问json数据
https://app.quicktype.io/使用这个网站创建一个json类