每当数据更新时如何向用户发送通知[Flutter]?

时间:2019-01-12 12:59:54

标签: dart flutter

我正在颤抖地调用RESFUL NODE API,以获取有关向服务器提供电子邮件和密码的一些数据,并且它运行良好。我没有将这些数据存储在任何数据库中,因为我是从api中的某个地方抓取数据并将其发送回用户的。现在,我想在数据更改时通知用户。我所苦苦挣扎的是,如何知道是否以JSON的形式更改了或不更改,因为由于异步行为,我的api不管数据是否更改,其api都会以不同的顺序返回数据。那么,如何在数据更改时通知我的用户?这是我的flutter应用程序代码:

class UserPage extends StatefulWidget{
  Map formData;
  UserPage(formData){
      this.formData = formData;
  }
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _UserPageState();
  }
}

class _UserPageState extends State<UserPage> {
  List AssignmentData;
  List<dynamic> newData;
  String LoginFailedMsg ='';
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

  void ValidateResponse() async{
    await http.post("xxxxxxxxxxxxxxxxxxxxxx",
        headers: {
          'Content-type': 'application/x-www-form-urlencoded',
          'Accept' : 'application/json'
        },
        body: widget.formData
    ).then((response){
        if(response.statusCode == 200){
          // Login Successful
          setState(() {
              Fluttertoast.showToast(
                  msg: "Assignments Refreshed",
                  toastLength: Toast.LENGTH_SHORT,
                  gravity: ToastGravity.BOTTOM,
                  timeInSecForIos: 1
              );
              AssignmentData  = json.decode(response.body);

          });
        }
        else{
          //Login Failed
          setState(() {
            LoginFailedMsg = response.body;
            print(LoginFailedMsg);
          });
        }
    });
  }
@override
  void initState() {
    // TODO: implement initState
    ValidateResponse();
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    var android = new AndroidInitializationSettings('@mipmap/ic_launcer');
    var ios = new IOSInitializationSettings();
    var initSettings = new InitializationSettings(android, ios);
    flutterLocalNotificationsPlugin.initialize(initSettings,onSelectNotification: onSelectNotification);
  }
  Future onSelectNotification(String payload){
    debugPrint('payload:$payload');
    showDialog(context: context,builder: (_)=>
    new AlertDialog(
        title: new Text('Notification'),
        content: new Text('$payload')
    )
    );
  }
  @override
  Widget build(BuildContext context){

    final AssignmentImage = Image.asset('assets/assignment_img.png',fit: BoxFit.fitWidth,);

    return new Scaffold(
        backgroundColor: Colors.white,
        appBar: new AppBar(
          title: Text('Pending Assignments'),
          backgroundColor: Colors.red,
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.refresh),
              color: Colors.black,
              tooltip: 'Refresh Assignments',
              onPressed: ValidateResponse,
            )
          ],
        ),
        body: new Column(
        children: <Widget> [Text(LoginFailedMsg),
          new Expanded(child: ListView.builder(
            shrinkWrap: true,
              itemCount: AssignmentData == null ? 0 : AssignmentData.length,
              itemBuilder: (BuildContext context,int index) {
                return new Column(
                      children: <Widget>[SizedBox(height: 15,),
                        Text(
                            AssignmentData[index]['course'],
                            style: TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.bold
                            ),
                        ),
                SizedBox(height: 15,),
                new ListView.builder(
                    physics: ClampingScrollPhysics(),
                  shrinkWrap: true,
                          itemCount: AssignmentData[index]['pending_assignment'].length,
                          itemBuilder: (BuildContext context, int NoOfAssignments){
                            return new Container(
                                margin: const EdgeInsets.all(5.0),
                                padding: const EdgeInsets.all(3.0),
                                decoration: new BoxDecoration(
                                    border: new Border.all(color: Colors.white12),
                                  color: Colors.white,

                                  boxShadow: [BoxShadow(color: Colors.black,blurRadius:4.0, ),]
                                ),
                            child: new Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Text(
                                    'Name: '+AssignmentData[index]['pending_assignment'][NoOfAssignments]['name'],
                                    style: TextStyle(
                                      fontSize: 15,
                                      fontStyle: FontStyle.italic,
                                      fontWeight: FontWeight.w600
                                    ),
                                ),
                                SizedBox(height: 20,),
                                Text(
                                    'Due Date: '+AssignmentData[index]['pending_assignment'][NoOfAssignments]['dueDate'],
                                    style: TextStyle(
                                        fontSize: 15,
                                        fontStyle: FontStyle.italic,
                                        fontWeight: FontWeight.w500
                                    ),
                                ),
                                SizedBox(height: 20,),
                                RaisedButton(
                                  elevation: 6,
                                child: Text(
                                  'Link: Open it',
                                  style: TextStyle(
                                      fontSize: 15,
                                      fontStyle: FontStyle.italic
                                  ),
                                ),
                                  onPressed: () => LauncUrl(AssignmentData[index]['pending_assignment'][NoOfAssignments]['assignmentLink']).launchURL(),
                                )
                              ]

                            )
                            );
                          }
                )
                      ]
                );
              })
          )
        ]
    )
    );

}
}

注意:我仅初始化了通知,而未在任何地方使用它。

0 个答案:

没有答案