lucky
lucky

Reputation: 315

How get Notification automatically flutter

I implemented a notification function can get alert from API and display it as a notififcation to user every one minute. the notification can display only if i press on button . I would like to change press action by script or function can do the same work automatically every 5 seconds . (without any press button ) .

Future<void> repeatNotification() async {
    var androidChannelSpecifics = AndroidNotificationDetails(
      'CHANNEL_ID 3',
      'CHANNEL_NAME 3',
      "CHANNEL_DESCRIPTION 3",
      playSound: true,
      importance: Importance.max,
      priority: Priority.high,
      sound: RawResourceAndroidNotificationSound('notification'),
      styleInformation: DefaultStyleInformation(true, true),
    );
    var iosChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        android: androidChannelSpecifics, iOS: iosChannelSpecifics);
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    String token = localStorage.getString('access_token');
    Map<String, String> headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token'
    };
    var response =
        await http.get(Uri.parse(ApiUtil.GET_ALERT), headers: headers);
    var data = json.decode(response.body);
    var dataa = (data['data']['data']['data'][0]);    
    if (data['status'] == 200) {
      flutterLocalNotificationsPlugin.periodicallyShow(
          0,
          dataa['boxName'],
          dataa['alert_description'],
          RepeatInterval.everyMinute,
          platformChannelSpecifics);
    } else {
      print("no message");
    }
 @override
  bool get wantKeepAlive => true;
  @override
  Widget build(BuildContext context) {
    Color color;
    Widget body = new FutureBuilder<UserAlert>(
        future: boxApi.getAlert(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return new ListView.builder(
                itemCount: snapshot.data.alerts.length,
                itemBuilder: (context, index) {
                  var alert = snapshot.data.alerts[index].alertLevel;
                  switch (alert) {
                    case "danger":
                      color = Colors.red;
                      break;
                    case "warning":
                      color = Colors.yellow;
                      break;
                    case "info":
                      color = Colors.green;
                      break;
                    default:
                      color = Colors.grey;
                  }
                  var boxName = snapshot.data.alerts[index].boxName;
                  var date = snapshot.data.alerts[index].alertDate;
                  var time = snapshot.data.alerts[index].alertTime;
                  var description =
                      snapshot.data.alerts[index].alertDescription;
                  return Card(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                 
                        ListTile(
                          title: Text("$date" + "  " + "$time"),
                          subtitle: Text("$description"),
                          trailing: Text("$boxName"),
                          leading: Transform.translate(
                            offset: const Offset(-15.0, 0.0),
                            child: Container(
                             
                              color: color,
                              child: SizedBox(
                                width: 5,
                                height: 100,
               
          } else {
            return new Center(
              child: new CircularProgressIndicator(),
            );
          }
        });

    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () => //Or whenever you actually want to trigger it
              _showNotification(),
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
        body: body);
  }
}

how i can replace buutton action ??

Upvotes: 1

Views: 422

Answers (1)

Prabhanshu Tiwari
Prabhanshu Tiwari

Reputation: 302

Here is a sample code that will help you run perform action for a certain time repeatation.

const _time = const Duration(minutes:5) ;                 
new Timer.periodic(_time, (Timer t) => print('flutter'));

Upvotes: 1

Related Questions