0% found this document useful (0 votes)
137 views

Notification in Flutter

This document contains code for an ActivityScreen in a Flutter Instagram clone app. It retrieves activity data from a database and displays it in a list. It also implements local notifications to notify the user about certain activities like a follow or comment. The screen displays each activity with details like the user, timestamp, and associated post. It links to other screens like profile or comment pages when tapped.

Uploaded by

smama hsn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

Notification in Flutter

This document contains code for an ActivityScreen in a Flutter Instagram clone app. It retrieves activity data from a database and displays it in a list. It also implements local notifications to notify the user about certain activities like a follow or comment. The screen displays each activity with details like the user, timestamp, and associated post. It links to other screens like profile or comment pages when tapped.

Uploaded by

smama hsn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

//Final Activity Screen Was with LOCAL NotificaTIONS

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:instagram/utilities/custom_navigation.dart';
import 'package:instagram/utilities/themes.dart';
import 'package:instagram/common_widgets/user_badges.dart';
import 'package:timeago/timeago.dart' as timeago;

import 'package:instagram/services/services.dart';
import 'package:instagram/models/models.dart';
import 'package:instagram/screens/screens.dart';
import 'package:instagram/utilities/constants.dart';

class ActivityScreen extends StatefulWidget {


final User currentUser;

ActivityScreen({this.currentUser});

@override
_ActivityScreenState createState() => _ActivityScreenState();
}

class _ActivityScreenState extends State<ActivityScreen> {


List<Activity> _activities = [];
bool _isLoading = false;
FlutterLocalNotificationsPlugin fltrNotification;
bool isLast;
@override
void initState() {
super.initState();
_setupActivities();
//For Local Notifications
var androidInitilize =
new AndroidInitializationSettings('@mipmap/ic_launcher');
var iOSinitilize = new IOSInitializationSettings();
var initilizationsSettings =
new InitializationSettings(androidInitilize, iOSinitilize);
fltrNotification = new FlutterLocalNotificationsPlugin();
fltrNotification.initialize(initilizationsSettings,
onSelectNotification: notificationSelected);
}

_toShowNotification(String title, String description) {


_showNotification(title, description);
}

Future _showNotification(String title, String description) async {


var androidDetails = new AndroidNotificationDetails(
"Channel ID", "Solutuion Sol", "This is my channel",
importance: Importance.Max);
var iSODetails = new IOSNotificationDetails();
var generalNotificationDetails =
new NotificationDetails(androidDetails, iSODetails);

await fltrNotification.show(
0, title, description, generalNotificationDetails,
payload: "Task");
// var scheduledTime = DateTime.now().add(Duration(seconds: 0));
// fltrNotification.schedule(
// 1, "Time", "Notification", scheduledTime, generalNotificationDetails);
}

Future notificationSelected(String payload) async {


showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text("Notification : $payload"),
));
// Navigator.push(
// context,
// MaterialPageRoute(builder: (context) => ActivityScreen()),
// );
}

_setupActivities() async {
setState(() => _isLoading = true);
List<Activity> activities =
await DatabaseService.getActivities(widget.currentUser.id);
if (mounted) {
setState(() {
_activities = activities;
_isLoading = false;
});
}
}

_buildActivity(Activity activity, bool isLast) {


return FutureBuilder(
future: DatabaseService.getUserWithId(activity.fromUserId),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return SizedBox.shrink();
}
User user = snapshot.data;
return ListTile(
tileColor: Colors.grey[100],
leading: CircleAvatar(
radius: 25.0,
backgroundColor: Colors.grey,
backgroundImage: user.profileImageUrl.isEmpty
? AssetImage(placeHolderImageRef)
: CachedNetworkImageProvider(user.profileImageUrl),
),
title: activity.isFollowEvent == true
? Row(
children: <Widget>[
Text('${user.name}', style: kFontWeightBoldTextStyle),
UserBadges(user: user, size: 15, secondSizedBox: false),
SizedBox(
width: 5,
child: activity.isFollowEvent == true && isLast == true
? _toShowNotification(
'InstaDart', '${user.name} started following you')
: Container(),
),
Expanded(
child: Text(
'started following you',
overflow: TextOverflow.ellipsis,
),
),
],
)
: activity.isCommentEvent == true
? Container(
child: Row(
children: <Widget>[
Text('${user.name}', style: kFontWeightBoldTextStyle),
UserBadges(
user: user, size: 15, secondSizedBox: false),
SizedBox(
width: 5,
child: activity.isCommentEvent == true &&
isLast == true
? _toShowNotification('InstaDart',
'${user.name} commented: "${activity.comment}')
: Container(),
),
Expanded(
child: Text(
'commented: "${activity.comment}',
overflow: TextOverflow.ellipsis,
)),
],
),
)
: Row(
children: <Widget>[
Text('${user.name}', style: kFontWeightBoldTextStyle),
UserBadges(user: user, size: 15, secondSizedBox: false),
SizedBox(
width: 5,
child: activity.isFollowEvent == false &&
activity.isCommentEvent == false &&
isLast == true
? _toShowNotification(
'InstaDart', '${user.name} liked your post')
: Container(),
),
Expanded(
child: Text(
'liked your post',
overflow: TextOverflow.ellipsis,
),
),
],
),
subtitle: Text(
timeago.format(activity.timestamp.toDate()),
),
trailing: activity.postImageUrl == null
? SizedBox.shrink()
: CachedNetworkImage(
imageUrl: activity.postImageUrl,
fadeInDuration: Duration(milliseconds: 500),
height: 40.0,
width: 40.0,
fit: BoxFit.cover,
),
onTap: activity.isFollowEvent
? () => CustomNavigation.navigateToUserProfile(
context: context,
currentUserId: widget.currentUser.id,
isCameFromBottomNavigation: false,
userId: activity.fromUserId)
: () async {
Post post = await DatabaseService.getUserPost(
widget.currentUser.id,
activity.postId,
);
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => CommentsScreen(
postStatus: PostStatus.feedPost,
post: post,
likeCount: post.likeCount,
author: widget.currentUser,
),
),
);
},
);
},
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).appBarTheme.color,
title: Text(
'Activity',
),
),
body: RefreshIndicator(
onRefresh: () => _setupActivities(),
child: _isLoading
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: _activities.length,
itemBuilder: (BuildContext context, int index) {
Activity activity = _activities[index];
isLast = false;

if (index == 0) {
isLast = true;
}
if (activity.isMessageEvent == true ||
activity.isLikeMessageEvent == true) {
return SizedBox.shrink();
}
return _buildActivity(activity, isLast);
},
),
),
);
}
}

You might also like