Stream Feed official Flutter SDK

Official Dart Client for Stream Activity Feeds The official Dart client for Stream Activity Feeds a service for building feed applications. This library can be used on any Dart project and on both mobile and web apps with Flutter.

🔗 Quick Links

  • Register to get an API key for Stream Activity Feeds
  • Tutorial to learn how to setup a timeline feed, follow other feeds and post new activities.
  • Stream Activity Feeds UI Kit to jumpstart your design with notifications and social feeds

🛠 Installation

Install from pub 

Next step is to add stream_feed to your dependencies, to do that just open pubspec.yaml and add it inside the dependencies section.

dependencies:
  flutter:
    sdk: flutter

  stream_feed: ^[latest-version]

Using with Flutter

This package can be integrated into Flutter applications. Remember to not expose the App Secret in your Flutter web apps, mobile apps, or other non-trusted environments like desktop apps.

🔌 Usage

API client setup Serverside + Clientside

If you want to use the API client directly on your web/mobile app you need to generate a user token server-side and pass it.

Server-side token generation


// Instantiate a new client (server side)
const apiKey = 'my-API-key';
const secret = 'my-API-secret';

// Instantiate a new client (server side)
var client = StreamFeedClient.connect(apiKey, secret: secret, runner: Runner.server);

// Optionally supply the app identifier and an options object specifying the data center to use and timeout for requests (15s)
client = StreamFeedClient.connect(apiKey,
  secret: secret,
  runner: Runner.server,
  appId: 'yourappid',
  runner: Runner.server,
  options: StreamHttpClientOptions(
    location: Location.usEast,
    connectTimeout: Duration(seconds: 15),
  ),
);

// Create a token for user with id "the-user-id"
final userToken = client.frontendToken('the-user-id');

:warning: for security, you must never expose your API secret or generated client side token, and it's highly recommended to use exp claim in client side token.

Client API init

// Instantiate new client with a user token
var client = StreamFeedClient.connect(apiKey, token: Token('userToken'));

🔮 Examples

// Instantiate a feed object server side
var user1 = client.flatFeed('user', '1');

// Get activities from 5 to 10 (slow pagination)
final activities = await user1.getActivities(limit: 5, offset: 5);
// Filter on an id less than a given UUID
final filtered_activities = await user1.getActivities(
      limit: 5,
      filter: Filter().idLessThan('e561de8f-00f1-11e4-b400-0cc47a024be0')

// All API calls are performed asynchronous and return a Promise object
await user1
    .getActivities(
        limit: 5,
        filter: Filter().idLessThan('e561de8f-00f1-11e4-b400-0cc47a024be0'))
    .then((value) => /* on success */
        print(value))
    .onError((error,
              stackTrace) => /* on failure, reason.error contains an explanation */
        print(error));

// Create a new activity
final activity = Activity( actor: '1', verb: 'tweet', object: '1', foreignId: 'tweet:1' );
final added_activity = await user1.addActivity(activity);
// Create a bit more complex activity
final complex_activity = Activity(
    actor: '1',
    verb: 'run',
    object: '1',
    foreignId: 'run:1',
    extraData: {
      'course': {'name': 'Golden Gate park', 'distance': 10},
      'participants': ['Thierry', 'Tommaso'],
      'started_at': DateTime.now().toIso8601String(),
    },
  );
final added_complex_activity = await user1.addActivity(complex_activity);

// Remove an activity by its id
await user1.removeActivityById('e561de8f-00f1-11e4-b400-0cc47a024be0');
// or remove by the foreign id
await user1.removeActivityByForeignId('tweet:1');

// mark a notification feed as read
await notification1.getActivities(
  marker: ActivityMarker().allRead(),
);


// mark a notification feed as seen
await notification1.getActivities(
  marker: ActivityMarker().allSeen(),
);

// Follow another feed
await user1.follow(client.flatFeed('flat', '42'));

// Stop following another feed
await user1.unfollow(client.flatFeed('flat', '42'));

// Stop following another feed while keeping previously published activities
// from that feed
await user1.unfollow(client.flatFeed('flat', '42'), keepHistory: true);

// Follow another feed without copying the history
await user1.follow(client.flatFeed('flat', '42'), activityCopyLimit: 0);

// List followers, following
await user1.followers(limit: 10, offset: 10);
await user1.following(limit: 10, offset: 0);


await user1.follow(client.flatFeed('flat', '42'));

// adding multiple activities
const activities = [
  Activity(actor: '1', verb: 'tweet', object: '1'),
  Activity(actor: '2', verb: 'tweet', object: '3'),
];
await user1.addActivities(activities);

// specifying additional feeds to push the activity to using the to param
// especially useful for notification style feeds
final to = FeedId.fromIds(['user:2', 'user:3']);
final activityTo = Activity(
  to: to,
  actor: '1',
  verb: 'tweet',
  object: '1',
  foreignId: 'tweet:1',
);
await user1.addActivity(activityTo);


// adding one activity to multiple feeds
final feeds = FeedId.fromIds(['flat:1', 'flat:2', 'flat:3', 'flat:4']);
final activityTarget = Activity(
  actor: 'User:2',
  verb: 'pin',
  object: 'Place:42',
  target: 'Board:1',
);

// ⚠️ server-side only!
await client.batch.addToMany(activityTarget, feeds!);

// Batch create follow relations (let flat:1 follow user:1, user:2 and user:3 feeds in one single request)
const follows = [
  Follow('flat:1', 'user:1'),
  Follow('flat:1', 'user:2'),
  Follow('flat:1', 'user:3'),
];

// ⚠️ server-side only!
await client.batch.followMany(follows);

// Updating parts of an activity
final set = {
  'product.price': 19.99,
  shares: {
    facebook: '...',
    twitter: '...',
  },
};
final unset = ['daily_likes', 'popularity'];

// ...by ID
final update = ActivityUpdate.withId( '54a60c1e-4ee3-494b-a1e3-50c06acb5ed4', set, unset);
await client.updateActivityById(update);
// ...or by combination of foreign ID and time
const timestamp = DateTime.now();
const foreignID= 'product:123';
final update2 = ActivityUpdate.withForeignId(
  foreignID,
  timestamp,
  set,
  unset,
);
await client.updateActivityById(update2);


// update the 'to' fields on an existing activity
// client.flatFeed("user", "ken").function (foreign_id, timestamp, new_targets, added_targets, removed_targets)
// new_targets, added_targets, and removed_targets are all arrays of feed IDs
// either provide only the `new_targets` parameter (will replace all targets on the activity),
// OR provide the added_targets and removed_targets parameters
// NOTE - the updateActivityToTargets method is not intended to be used in a browser environment.
await client.flatFeed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, ['feed:1234']);
await client.flatFeed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, null, ['feed:1234']);
await client.flatFeed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, null, null, ['feed:1234']);

Realtime (Faye)

Stream uses Faye for realtime notifications. Below is quick guide to subscribing to feed changes


// ⚠️ userToken is generated server-side (see previous section)
final client = StreamFeedClient.connect('YOUR_API_KEY', token: userToken,appId: 'APP_ID');
final user1 = client.flatFeed('user', '1');

// subscribe to the changes
final subscription = await userFeed.subscribe((message) => print(message));
// now whenever something changes to the feed user 1
// the callback will be called

// To cancel a subscription you can call cancel on the
// object returned from a subscribe call.
// This will remove the listener from this channel.
await subscription.cancel();

Docs are available on GetStream.io.

🔮 Example Project

There is a detailed Flutter example project in the example folder. You can directly run and play on it.

Contributing

Code conventions

  • Make sure that you run dartfmt before commiting your code
  • Make sure all public methods and functions are well documented

Running tests

  • run flutter test

Releasing a new version

update the package version on pubspec.yaml and version.dart

add a changelog entry on CHANGELOG.md

run flutter pub publish to publish the package

Watch models and generate JSON code

JSON serialization relies on code generation; make sure to keep that running while you make changes to the library

flutter pub run build_runner watch

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add stream_feed

With Flutter:

 $ flutter pub add stream_feed

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  stream_feed: ^0.3.0

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:stream_feed/stream_feed.dart'; 

example/main.dart

import 'dart:io';

import 'package:stream_feed/stream_feed.dart';

Future<void> main() async {
  final env = Platform.environment;
  final secret = env['secret'];
  final apiKey = env['apiKey'];
  final appId = env['appId'];
  final clientWithSecret = StreamFeedClient.connect(
    apiKey!,
    secret: secret,
    runner: Runner.server,
  );

  final chris = clientWithSecret.flatFeed('user', 'chris');

  // Add an Activity; message is a custom field - tip: you can add unlimited custom fields!
  final addedPicture = await chris.addActivity(
    const Activity(
      actor: 'chris',
      verb: 'add',
      object: 'picture:10',
      foreignId: 'picture:10',
      extraData: {'message': 'Beautiful bird!'},
    ),
  );

  // Create a following relationship between Jack's "timeline" feed and Chris' "user" feed:
  final jack = clientWithSecret.flatFeed('timeline', 'jack');
  await jack.follow(chris);

// Read Jack's timeline and Chris' post appears in the feed:
  final results = await jack.getActivities(limit: 10);

// Remove an Activity by referencing it's Foreign Id:
  await chris.removeActivityByForeignId('picture:10');

  // Instantiate a feed using feed group 'user' and user id '1'
  final user1 = clientWithSecret.flatFeed('user', '1');

// Create an activity object
  var activity = Activity(actor: 'User:1', verb: 'pin', object: 'Place:42');

// Add an activity to the feed
  final pinActivity = await user1.addActivity(activity);

// Create a bit more complex activity
  activity =
      Activity(actor: 'User:1', verb: 'run', object: 'Exercise:42', extraData: {
    'course': const {'name': 'Golden Gate park', 'distance': 10},
    'participants': const ['Thierry', 'Tommaso'],
    'started_at': DateTime.now().toIso8601String(),
    'foreign_id': 'run:1',
    'location': const {
      'type': 'point',
      'coordinates': [37.769722, -122.476944]
    }
  });

  final exercise = await user1.addActivity(activity);

  // Get 5 activities with id less than the given UUID (Faster - Recommended!)
  var response = await user1.getActivities(
    limit: 5,
    filter: Filter().idLessThan('e561de8f-00f1-11e4-b400-0cc47a024be0'),
  );

// Get activities from 5 to 10 (Pagination-based - Slower)
  response = await user1.getActivities(offset: 0, limit: 5);
// Get activities sorted by rank (Ranked Feeds Enabled):
  // response = await userFeed.getActivities(limit: 5, ranking: "popularity");//must be enabled

// Server-side
  var client = StreamFeedClient.connect(
    apiKey,
    secret: secret,
    appId: appId,
    runner: Runner.server,
    options: StreamHttpClientOptions(location: Location.usEast),
  );

  final userToken = client.frontendToken('user.id');

// Client-side
  client = StreamFeedClient.connect(
    apiKey,
    token: userToken,
    appId: appId,
  );

  // Remove an activity by its id
  await user1.removeActivityById(addedPicture.id!);

// Remove activities foreign_id 'run:1'
  await user1.removeActivityByForeignId('run:1');

  final now = DateTime.now();

  activity = Activity(
      actor: "1",
      verb: "like",
      object: "3",
      time: now,
      foreignId: "like:3",
      extraData: {
        'popularity': 100,
      });

// first time the activity is added
  final like = await user1.addActivity(activity);

// send the update to the APIs
  user1.updateActivityById(id: like.id!,
      // update the popularity value for the activity
      set: {
        'popularity': 10,
      });

  // partial update by activity ID
  await user1.updateActivityById(id: exercise.id!, set: {
    'course.distance': 12,
    'shares': {
      'facebook': '...',
      'twitter': '...',
    },
  }, unset: [
    'location',
    'participants'
  ]);

// partial update by foreign ID
// user1.updateActivityByForeignId(
//   foreignId: 'product:123',
//   time: DateTime.parse(('2016-11-10T13:20:00.000000'),
//   set: {
//     ...
//   },
//   unset: [
//     ...
//   ]
// );

//Batching Partial Updates TODO
  // final now = DateTime.now();
  final first_activity = Activity(
    actor: '1',
    verb: 'add',
    object: '1',
    foreignId: 'activity_1',
    time: DateTime.now(),
  );

// Add activity to activity feed:
  final firstActivityAdded = await user1.addActivity(first_activity);

  final second_activity = Activity(
      actor: '1', verb: 'add', object: '1', foreignId: 'activity_2', time: now);

  final secondActivityAdded = await user1.addActivity(second_activity);

  //Following Feeds
  // timeline:timeline_feed_1 follows user:user_42:
  final timelineFeed1 =
      clientWithSecret.flatFeed('timeline', 'timeline_feed_1');
  final user42feed = clientWithSecret.flatFeed('user', 'user_42');
  await timelineFeed1.follow(user42feed);

// Follow feed without copying the activities:
  await timelineFeed1.follow(user42feed, activityCopyLimit: 0);

  //Unfollowing feeds
  // Stop following feed user_42 - purging history:
  await timelineFeed1.unfollow(user42feed);

// Stop following feed user_42 but keep history of activities:
  await timelineFeed1.unfollow(user42feed, keepHistory: true);

//Reading Feed Followers
  // List followers
  await user1.followers(limit: 10, offset: 10);
  // Retrieve last 10 feeds followed by user_feed_1
  await user1.following(offset: 0, limit: 10);

// Retrieve 10 feeds followed by user_feed_1 starting from the 11th
  await user1.following(offset: 10, limit: 10);

// Check if user1 follows specific feeds
  await user1.following(
      offset: 0,
      limit: 2,
      filter: [FeedId.id('user:42'), FeedId.id('user:43')]);

  // get follower and following stats of the feed
  await clientWithSecret.flatFeed('user', 'me').followStats();

// get follower and following stats of the feed but also filter with given slugs
// count by how many timelines follow me
// count by how many markets are followed
  await clientWithSecret
      .flatFeed('user', 'me')
      .followStats(followerSlugs: ['timeline'], followingSlugs: ['market']);
//Realtime
  final frontendToken = clientWithSecret.frontendToken('john-doe');

//Use Case: Mentions
  // Add the activity to Eric's feed and to Jessica's notification feed
  activity = Activity(
    actor: 'user:Eric',
    extraData: {
      'message': "@Jessica check out getstream.io it's awesome!",
    },
    verb: 'tweet',
    object: 'tweet:id',
    to: [FeedId.id('notification:Jessica')],
  );

  final tweet = await user1.addActivity(activity);

  // add a like reaction to the activity with id activityId
  await clientWithSecret.reactions.add('like', tweet.id!, userId: 'userId');

// adds a comment reaction to the activity with id activityId
  await clientWithSecret.reactions.add('comment', tweet.id!,
      data: {'text': 'awesome post!'}, userId: 'userId');

// for server side auth, userId is required
  final comment = await clientWithSecret.reactions.add('comment', tweet.id!,
      data: {'text': 'awesome post!'}, userId: 'userId');

// first let's read current user's timeline feed and pick one activity
  final activities =
      await clientWithSecret.flatFeed('user', '1').getActivities();

// then let's add a like reaction to that activity
  final otherLike = await clientWithSecret.reactions
      .add('like', activities.first.id!, userId: 'userId');

// retrieve all kind of reactions for an activity
  await clientWithSecret.reactions.filter(
      LookupAttribute.activityId, '5de5e4ba-add2-11eb-8529-0242ac130003');

// retrieve first 10 likes for an activity
  await clientWithSecret.reactions.filter(
      LookupAttribute.activityId, '5de5e4ba-add2-11eb-8529-0242ac130003',
      kind: 'like', limit: 10);

// retrieve the next 10 likes using the id_lt param
  await clientWithSecret.reactions.filter(
    LookupAttribute.activityId,
    '5de5e4ba-add2-11eb-8529-0242ac130003',
    kind: 'like',
    filter: Filter().idLessThan('e561de8f-00f1-11e4-b400-0cc47a024be0'),
  );

  // await clientWithSecret.reactions
  //     .update(comment.id!, data: {'text': 'love it!'});

// read bob's timeline and include most recent reactions to all activities and their total count
  await clientWithSecret.flatFeed('timeline', 'bob').getEnrichedActivities(
        flags: EnrichmentFlags().withRecentReactions().withReactionCounts(),
      );

// read bob's timeline and include most recent reactions to all activities and her own reactions
  await clientWithSecret.flatFeed('timeline', 'bob').getEnrichedActivities(
        flags: EnrichmentFlags().withRecentReactions().withReactionCounts(),
      );

// adds a comment reaction to the activity and notifies Thierry's notification feed
  await clientWithSecret.reactions.add(
      'comment', '5de5e4ba-add2-11eb-8529-0242ac130003',
      data: {'text': "@thierry great post!"},
      userId: 'userId',
      targetFeeds: [FeedId.id('notification:thierry')]);

  // adds a like to the previously created comment
  await clientWithSecret.reactions
      .addChild('like', comment.id!, userId: 'userId');
  await clientWithSecret.reactions.delete(comment.id!);
//Adding Collections
  // await client.collections.add(
  //   'food',
  //   {'name': 'Cheese Burger', 'rating': '4 stars'},
  //   entryId: 'cheese-burger',
  // );//will throw an error if entry-id already exists

// if you don't have an id on your side, just use null as the ID and Stream will generate a unique ID
  final entry = await clientWithSecret.collections
      .add('food', {'name': 'Cheese Burger', 'rating': '4 stars'});
  await clientWithSecret.collections.get('food', entry.id!);
  await clientWithSecret.collections.update(
      entry.copyWith(data: {'name': 'Cheese Burger', 'rating': '1 star'}));
  await clientWithSecret.collections.delete('food', entry.id!);

  // first we add our object to the food collection
  final cheeseBurger = await clientWithSecret.collections.add('food', {
    'name': 'Cheese Burger',
    'ingredients': ['cheese', 'burger', 'bread', 'lettuce', 'tomato'],
  });

// the object returned by .add can be embedded directly inside of an activity
  await user1.addActivity(Activity(
    actor: createUserReference('userId'),
    verb: 'grill',
    object: cheeseBurger.ref,
  ));

// if we now read the feed, the activity we just added will include the entire full object
  await user1.getEnrichedActivities();

// we can then update the object and Stream will propagate the change to all activities
  await clientWithSecret.collections.update(cheeseBurger.copyWith(data: {
    'name': 'Amazing Cheese Burger',
    'ingredients': ['cheese', 'burger', 'bread', 'lettuce', 'tomato'],
  }));

  // First create a collection entry with upsert api
  await clientWithSecret.collections.upsert('food', [
    CollectionEntry(id: 'cheese-burger', data: {'name': 'Cheese Burger'}),
  ]);

// Then create a user
  await clientWithSecret.user('john-doe').getOrCreate({
    'name': 'John Doe',
    'occupation': 'Software Engineer',
    'gender': 'male',
  });

// Since we know their IDs we can create references to both without reading from APIs
  final cheeseBurgerRef =
      clientWithSecret.collections.entry('food', 'cheese-burger').ref;
  final johnDoeRef = clientWithSecret.user('john-doe').ref;

// And then add an activity with these references
  await clientWithSecret.flatFeed('user', 'john').addActivity(Activity(
        actor: johnDoeRef,
        verb: 'eat',
        object: cheeseBurgerRef,
      ));

  client = StreamFeedClient.connect(apiKey, token: frontendToken);
// ensure the user data is stored on Stream
  await client.setUser({
    'name': 'John Doe',
    'occupation': 'Software Engineer',
    'gender': 'male'
  });

  // create a new user, if the user already exist an error is returned
  // await client.user('john-doe').create({
  //   'name': 'John Doe',
  //   'occupation': 'Software Engineer',
  //   'gender': 'male'
  // });

// get or create a new user, if the user already exist the user is returned
  await client.user('john-doe').getOrCreate({
    'name': 'John Doe',
    'occupation': 'Software Engineer',
    'gender': 'male'
  });

//retrieving users
  await client.user('john-doe').get();

  await client.user('john-doe').update({
    'name': 'Jane Doe',
    'occupation': 'Software Engineer',
    'gender': 'female'
  });

  //removing users
  await client.user('john-doe').delete();

  // Read the personalized feed for a given user
  var params = {'user_id': 'john-doe', 'feed_slug': 'timeline'};

  // await clientWithSecret.personalization
  //     .get('personalized_feed', params: params);

//Our data science team will typically tell you which endpoint to use
  params = {
    'user_id': 'john-doe',
    'source_feed_slug': 'timeline',
    'target_feed_slug': 'user'
  };

  // await client.personalization
  //     .get('discovery_feed', params: params);
  final analytics = StreamAnalytics(apiKey, secret: secret);
  analytics.setUser(id: 'id', alias: 'alias');
  await analytics.trackEngagement(
    Engagement(
      // the label for the engagement, ie click, retweet etc.
      label: 'click',
      content: Content(
          // the ID of the content that the user clicked
          foreignId: FeedId.id('tweet:34349698')),
      // score between 0 and 100 indicating the importance of this event
      // IE. a like is typically a more significant indicator than a click
      score: 2,
      // (optional) the position in a list of activities
      position: 3,
      boost: 2,

      // (optional) the feed the user is looking at
      feedId: FeedId('user', 'thierry'),
      // (optional) the location in your app. ie email, profile page etc
      location: 'profile_page',
    ),
  );

  await analytics.trackImpression(
    Impression(
      feedId: FeedId('timeline', 'tom'),
      location: 'profile_page',
      contentList: [
        Content(
          data: const {
            'foreign_id': 'post:42',
            'actor': {'id': 'user:2353540'},
            'verb': 'share',
            'object': {'id': 'song:34349698'},
          },
          foreignId: FeedId.id('post:42'),
        )
      ],
    ),
  );

  const imageURI = 'test/assets/test_image.jpeg';

  // uploading an image from the filesystem
  final imageUrl = await client.images.upload(AttachmentFile(path: imageURI));

  await client.images.getCropped(
    imageUrl!,
    const Crop(50, 50),
  );

  await client.images.getResized(
    imageUrl,
    const Resize(50, 50),
  );

// deleting an image using the url returned by the APIs
  await client.images.delete(imageUrl);

  const fileURI = 'test/assets/example.pdf';
  // uploading a file from the filesystem
  final fileUrl = await client.files.upload(AttachmentFile(path: fileURI));

// deleting a file using the url returned by the APIs
  await client.files.delete(fileUrl!);

  final preview = await client.og('http://www.imdb.com/title/tt0117500/');
} 

Download Details:

Author: GetStream

Source Code: https://github.com/GetStream/stream-feed-flutter

#flutter #stream 

What is GEEK

Buddha Community

Stream Feed official Flutter SDK

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

InteractiveViewer is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider and RangeSliderDatePicker with support for date range and time picker with the new style.

flutter_DatePicker

New pubspec.yaml format

Other than these widget updates there is some update within the project also like in pubspec.yaml file format. If you are a flutter plugin publisher then your old pubspec.yaml  is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dartmethod.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Terry  Tremblay

Terry Tremblay

1598396940

What is Flutter and why you should learn it?

Flutter is an open-source UI toolkit for mobile developers, so they can use it to build native-looking** Android and iOS** applications from the same code base for both platforms. Flutter is also working to make Flutter apps for Web, PWA (progressive Web-App) and Desktop platform (Windows,macOS,Linux).

flutter-mobile-desktop-web-embedded_min

Flutter was officially released in December 2018. Since then, it has gone a much stronger flutter community.

There has been much increase in flutter developers, flutter packages, youtube tutorials, blogs, flutter examples apps, official and private events, and more. Flutter is now on top software repos based and trending on GitHub.

Flutter meaning?

What is Flutter? this question comes to many new developer’s mind.

humming_bird_dart_flutter

Flutter means flying wings quickly, and lightly but obviously, this doesn’t apply in our SDK.

So Flutter was one of the companies that were acquired by **Google **for around $40 million. That company was based on providing gesture detection and recognition from a standard webcam. But later when the Flutter was going to release in alpha version for developer it’s name was Sky, but since Google already owned Flutter name, so they rename it to Flutter.

Where Flutter is used?

Flutter is used in many startup companies nowadays, and even some MNCs are also adopting Flutter as a mobile development framework. Many top famous companies are using their apps in Flutter. Some of them here are

Dream11

Dream11

NuBank

NuBank

Reflectly app

Reflectly app

Abbey Road Studios

Abbey Road Studios

and many more other apps. Mobile development companies also adopted Flutter as a service for their clients. Even I was one of them who developed flutter apps as a freelancer and later as an IT company for mobile apps.

Flutter as a service

#dart #flutter #uncategorized #flutter framework #flutter jobs #flutter language #flutter meaning #flutter meaning in hindi #google flutter #how does flutter work #what is flutter

Adobe XD plugin for Flutter with CodePen Tutorial

Recently Adobe XD releases a new version of the plugin that you can use to export designs directly into flutter widgets or screens. Yes, you read it right, now you can make and export your favorite design in Adobe XD and export all the design in the widget form or as a full-screen design, this can save you a lot of time required in designing.

What we will do?
I will make a simple design of a dialogue box with a card design with text over it as shown below. After you complete this exercise you can experiment with the UI. You can make your own components or import UI kits available with the Adobe XD.

#developers #flutter #adobe xd design export to flutter #adobe xd flutter code #adobe xd flutter code generator - plugin #adobe xd flutter plugin #adobe xd flutter plugin tutorial #adobe xd plugins #adobe xd to flutter #adobe xd tutorial #codepen for flutter.

Download Android SDK Manager and SDK Tools

In this tutorial, we’ll read about the Android SDK Manager. We will see what is SDK manager in Android and why and how it is important for Android. So, SDK stands for Software Development Kit, which is a collection of software tools required. SDK basically helps Android to download tools and recent versions of Android. Every time a new Android version is released, along with it is released an SDK corresponding to it. This SDK must be installed by the developers for the devices.
What is SDK Manager?
A Software development kit is a set of tools required for the development of applications for Android. It also ensures that the progress of App development goes as flat as pancakes. We need SDK irrespective of the language we are using. Android SDK comes wrapped up with the Android Studio these days. An Android SDK separates the tools, platforms and other components into packages. These can be downloaded from the SDK Manager.

#android tutorials #android sdk manager #android sdk manager download #android sdk tools #android studio sdk manager #sdk download #sdk manager #sdk tools

Stream Feed official Flutter SDK

Official Dart Client for Stream Activity Feeds The official Dart client for Stream Activity Feeds a service for building feed applications. This library can be used on any Dart project and on both mobile and web apps with Flutter.

🔗 Quick Links

  • Register to get an API key for Stream Activity Feeds
  • Tutorial to learn how to setup a timeline feed, follow other feeds and post new activities.
  • Stream Activity Feeds UI Kit to jumpstart your design with notifications and social feeds

🛠 Installation

Install from pub 

Next step is to add stream_feed to your dependencies, to do that just open pubspec.yaml and add it inside the dependencies section.

dependencies:
  flutter:
    sdk: flutter

  stream_feed: ^[latest-version]

Using with Flutter

This package can be integrated into Flutter applications. Remember to not expose the App Secret in your Flutter web apps, mobile apps, or other non-trusted environments like desktop apps.

🔌 Usage

API client setup Serverside + Clientside

If you want to use the API client directly on your web/mobile app you need to generate a user token server-side and pass it.

Server-side token generation


// Instantiate a new client (server side)
const apiKey = 'my-API-key';
const secret = 'my-API-secret';

// Instantiate a new client (server side)
var client = StreamFeedClient.connect(apiKey, secret: secret, runner: Runner.server);

// Optionally supply the app identifier and an options object specifying the data center to use and timeout for requests (15s)
client = StreamFeedClient.connect(apiKey,
  secret: secret,
  runner: Runner.server,
  appId: 'yourappid',
  runner: Runner.server,
  options: StreamHttpClientOptions(
    location: Location.usEast,
    connectTimeout: Duration(seconds: 15),
  ),
);

// Create a token for user with id "the-user-id"
final userToken = client.frontendToken('the-user-id');

:warning: for security, you must never expose your API secret or generated client side token, and it's highly recommended to use exp claim in client side token.

Client API init

// Instantiate new client with a user token
var client = StreamFeedClient.connect(apiKey, token: Token('userToken'));

🔮 Examples

// Instantiate a feed object server side
var user1 = client.flatFeed('user', '1');

// Get activities from 5 to 10 (slow pagination)
final activities = await user1.getActivities(limit: 5, offset: 5);
// Filter on an id less than a given UUID
final filtered_activities = await user1.getActivities(
      limit: 5,
      filter: Filter().idLessThan('e561de8f-00f1-11e4-b400-0cc47a024be0')

// All API calls are performed asynchronous and return a Promise object
await user1
    .getActivities(
        limit: 5,
        filter: Filter().idLessThan('e561de8f-00f1-11e4-b400-0cc47a024be0'))
    .then((value) => /* on success */
        print(value))
    .onError((error,
              stackTrace) => /* on failure, reason.error contains an explanation */
        print(error));

// Create a new activity
final activity = Activity( actor: '1', verb: 'tweet', object: '1', foreignId: 'tweet:1' );
final added_activity = await user1.addActivity(activity);
// Create a bit more complex activity
final complex_activity = Activity(
    actor: '1',
    verb: 'run',
    object: '1',
    foreignId: 'run:1',
    extraData: {
      'course': {'name': 'Golden Gate park', 'distance': 10},
      'participants': ['Thierry', 'Tommaso'],
      'started_at': DateTime.now().toIso8601String(),
    },
  );
final added_complex_activity = await user1.addActivity(complex_activity);

// Remove an activity by its id
await user1.removeActivityById('e561de8f-00f1-11e4-b400-0cc47a024be0');
// or remove by the foreign id
await user1.removeActivityByForeignId('tweet:1');

// mark a notification feed as read
await notification1.getActivities(
  marker: ActivityMarker().allRead(),
);


// mark a notification feed as seen
await notification1.getActivities(
  marker: ActivityMarker().allSeen(),
);

// Follow another feed
await user1.follow(client.flatFeed('flat', '42'));

// Stop following another feed
await user1.unfollow(client.flatFeed('flat', '42'));

// Stop following another feed while keeping previously published activities
// from that feed
await user1.unfollow(client.flatFeed('flat', '42'), keepHistory: true);

// Follow another feed without copying the history
await user1.follow(client.flatFeed('flat', '42'), activityCopyLimit: 0);

// List followers, following
await user1.followers(limit: 10, offset: 10);
await user1.following(limit: 10, offset: 0);


await user1.follow(client.flatFeed('flat', '42'));

// adding multiple activities
const activities = [
  Activity(actor: '1', verb: 'tweet', object: '1'),
  Activity(actor: '2', verb: 'tweet', object: '3'),
];
await user1.addActivities(activities);

// specifying additional feeds to push the activity to using the to param
// especially useful for notification style feeds
final to = FeedId.fromIds(['user:2', 'user:3']);
final activityTo = Activity(
  to: to,
  actor: '1',
  verb: 'tweet',
  object: '1',
  foreignId: 'tweet:1',
);
await user1.addActivity(activityTo);


// adding one activity to multiple feeds
final feeds = FeedId.fromIds(['flat:1', 'flat:2', 'flat:3', 'flat:4']);
final activityTarget = Activity(
  actor: 'User:2',
  verb: 'pin',
  object: 'Place:42',
  target: 'Board:1',
);

// ⚠️ server-side only!
await client.batch.addToMany(activityTarget, feeds!);

// Batch create follow relations (let flat:1 follow user:1, user:2 and user:3 feeds in one single request)
const follows = [
  Follow('flat:1', 'user:1'),
  Follow('flat:1', 'user:2'),
  Follow('flat:1', 'user:3'),
];

// ⚠️ server-side only!
await client.batch.followMany(follows);

// Updating parts of an activity
final set = {
  'product.price': 19.99,
  shares: {
    facebook: '...',
    twitter: '...',
  },
};
final unset = ['daily_likes', 'popularity'];

// ...by ID
final update = ActivityUpdate.withId( '54a60c1e-4ee3-494b-a1e3-50c06acb5ed4', set, unset);
await client.updateActivityById(update);
// ...or by combination of foreign ID and time
const timestamp = DateTime.now();
const foreignID= 'product:123';
final update2 = ActivityUpdate.withForeignId(
  foreignID,
  timestamp,
  set,
  unset,
);
await client.updateActivityById(update2);


// update the 'to' fields on an existing activity
// client.flatFeed("user", "ken").function (foreign_id, timestamp, new_targets, added_targets, removed_targets)
// new_targets, added_targets, and removed_targets are all arrays of feed IDs
// either provide only the `new_targets` parameter (will replace all targets on the activity),
// OR provide the added_targets and removed_targets parameters
// NOTE - the updateActivityToTargets method is not intended to be used in a browser environment.
await client.flatFeed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, ['feed:1234']);
await client.flatFeed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, null, ['feed:1234']);
await client.flatFeed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, null, null, ['feed:1234']);

Realtime (Faye)

Stream uses Faye for realtime notifications. Below is quick guide to subscribing to feed changes


// ⚠️ userToken is generated server-side (see previous section)
final client = StreamFeedClient.connect('YOUR_API_KEY', token: userToken,appId: 'APP_ID');
final user1 = client.flatFeed('user', '1');

// subscribe to the changes
final subscription = await userFeed.subscribe((message) => print(message));
// now whenever something changes to the feed user 1
// the callback will be called

// To cancel a subscription you can call cancel on the
// object returned from a subscribe call.
// This will remove the listener from this channel.
await subscription.cancel();

Docs are available on GetStream.io.

🔮 Example Project

There is a detailed Flutter example project in the example folder. You can directly run and play on it.

Contributing

Code conventions

  • Make sure that you run dartfmt before commiting your code
  • Make sure all public methods and functions are well documented

Running tests

  • run flutter test

Releasing a new version

update the package version on pubspec.yaml and version.dart

add a changelog entry on CHANGELOG.md

run flutter pub publish to publish the package

Watch models and generate JSON code

JSON serialization relies on code generation; make sure to keep that running while you make changes to the library

flutter pub run build_runner watch

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add stream_feed

With Flutter:

 $ flutter pub add stream_feed

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  stream_feed: ^0.3.0

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:stream_feed/stream_feed.dart'; 

example/main.dart

import 'dart:io';

import 'package:stream_feed/stream_feed.dart';

Future<void> main() async {
  final env = Platform.environment;
  final secret = env['secret'];
  final apiKey = env['apiKey'];
  final appId = env['appId'];
  final clientWithSecret = StreamFeedClient.connect(
    apiKey!,
    secret: secret,
    runner: Runner.server,
  );

  final chris = clientWithSecret.flatFeed('user', 'chris');

  // Add an Activity; message is a custom field - tip: you can add unlimited custom fields!
  final addedPicture = await chris.addActivity(
    const Activity(
      actor: 'chris',
      verb: 'add',
      object: 'picture:10',
      foreignId: 'picture:10',
      extraData: {'message': 'Beautiful bird!'},
    ),
  );

  // Create a following relationship between Jack's "timeline" feed and Chris' "user" feed:
  final jack = clientWithSecret.flatFeed('timeline', 'jack');
  await jack.follow(chris);

// Read Jack's timeline and Chris' post appears in the feed:
  final results = await jack.getActivities(limit: 10);

// Remove an Activity by referencing it's Foreign Id:
  await chris.removeActivityByForeignId('picture:10');

  // Instantiate a feed using feed group 'user' and user id '1'
  final user1 = clientWithSecret.flatFeed('user', '1');

// Create an activity object
  var activity = Activity(actor: 'User:1', verb: 'pin', object: 'Place:42');

// Add an activity to the feed
  final pinActivity = await user1.addActivity(activity);

// Create a bit more complex activity
  activity =
      Activity(actor: 'User:1', verb: 'run', object: 'Exercise:42', extraData: {
    'course': const {'name': 'Golden Gate park', 'distance': 10},
    'participants': const ['Thierry', 'Tommaso'],
    'started_at': DateTime.now().toIso8601String(),
    'foreign_id': 'run:1',
    'location': const {
      'type': 'point',
      'coordinates': [37.769722, -122.476944]
    }
  });

  final exercise = await user1.addActivity(activity);

  // Get 5 activities with id less than the given UUID (Faster - Recommended!)
  var response = await user1.getActivities(
    limit: 5,
    filter: Filter().idLessThan('e561de8f-00f1-11e4-b400-0cc47a024be0'),
  );

// Get activities from 5 to 10 (Pagination-based - Slower)
  response = await user1.getActivities(offset: 0, limit: 5);
// Get activities sorted by rank (Ranked Feeds Enabled):
  // response = await userFeed.getActivities(limit: 5, ranking: "popularity");//must be enabled

// Server-side
  var client = StreamFeedClient.connect(
    apiKey,
    secret: secret,
    appId: appId,
    runner: Runner.server,
    options: StreamHttpClientOptions(location: Location.usEast),
  );

  final userToken = client.frontendToken('user.id');

// Client-side
  client = StreamFeedClient.connect(
    apiKey,
    token: userToken,
    appId: appId,
  );

  // Remove an activity by its id
  await user1.removeActivityById(addedPicture.id!);

// Remove activities foreign_id 'run:1'
  await user1.removeActivityByForeignId('run:1');

  final now = DateTime.now();

  activity = Activity(
      actor: "1",
      verb: "like",
      object: "3",
      time: now,
      foreignId: "like:3",
      extraData: {
        'popularity': 100,
      });

// first time the activity is added
  final like = await user1.addActivity(activity);

// send the update to the APIs
  user1.updateActivityById(id: like.id!,
      // update the popularity value for the activity
      set: {
        'popularity': 10,
      });

  // partial update by activity ID
  await user1.updateActivityById(id: exercise.id!, set: {
    'course.distance': 12,
    'shares': {
      'facebook': '...',
      'twitter': '...',
    },
  }, unset: [
    'location',
    'participants'
  ]);

// partial update by foreign ID
// user1.updateActivityByForeignId(
//   foreignId: 'product:123',
//   time: DateTime.parse(('2016-11-10T13:20:00.000000'),
//   set: {
//     ...
//   },
//   unset: [
//     ...
//   ]
// );

//Batching Partial Updates TODO
  // final now = DateTime.now();
  final first_activity = Activity(
    actor: '1',
    verb: 'add',
    object: '1',
    foreignId: 'activity_1',
    time: DateTime.now(),
  );

// Add activity to activity feed:
  final firstActivityAdded = await user1.addActivity(first_activity);

  final second_activity = Activity(
      actor: '1', verb: 'add', object: '1', foreignId: 'activity_2', time: now);

  final secondActivityAdded = await user1.addActivity(second_activity);

  //Following Feeds
  // timeline:timeline_feed_1 follows user:user_42:
  final timelineFeed1 =
      clientWithSecret.flatFeed('timeline', 'timeline_feed_1');
  final user42feed = clientWithSecret.flatFeed('user', 'user_42');
  await timelineFeed1.follow(user42feed);

// Follow feed without copying the activities:
  await timelineFeed1.follow(user42feed, activityCopyLimit: 0);

  //Unfollowing feeds
  // Stop following feed user_42 - purging history:
  await timelineFeed1.unfollow(user42feed);

// Stop following feed user_42 but keep history of activities:
  await timelineFeed1.unfollow(user42feed, keepHistory: true);

//Reading Feed Followers
  // List followers
  await user1.followers(limit: 10, offset: 10);
  // Retrieve last 10 feeds followed by user_feed_1
  await user1.following(offset: 0, limit: 10);

// Retrieve 10 feeds followed by user_feed_1 starting from the 11th
  await user1.following(offset: 10, limit: 10);

// Check if user1 follows specific feeds
  await user1.following(
      offset: 0,
      limit: 2,
      filter: [FeedId.id('user:42'), FeedId.id('user:43')]);

  // get follower and following stats of the feed
  await clientWithSecret.flatFeed('user', 'me').followStats();

// get follower and following stats of the feed but also filter with given slugs
// count by how many timelines follow me
// count by how many markets are followed
  await clientWithSecret
      .flatFeed('user', 'me')
      .followStats(followerSlugs: ['timeline'], followingSlugs: ['market']);
//Realtime
  final frontendToken = clientWithSecret.frontendToken('john-doe');

//Use Case: Mentions
  // Add the activity to Eric's feed and to Jessica's notification feed
  activity = Activity(
    actor: 'user:Eric',
    extraData: {
      'message': "@Jessica check out getstream.io it's awesome!",
    },
    verb: 'tweet',
    object: 'tweet:id',
    to: [FeedId.id('notification:Jessica')],
  );

  final tweet = await user1.addActivity(activity);

  // add a like reaction to the activity with id activityId
  await clientWithSecret.reactions.add('like', tweet.id!, userId: 'userId');

// adds a comment reaction to the activity with id activityId
  await clientWithSecret.reactions.add('comment', tweet.id!,
      data: {'text': 'awesome post!'}, userId: 'userId');

// for server side auth, userId is required
  final comment = await clientWithSecret.reactions.add('comment', tweet.id!,
      data: {'text': 'awesome post!'}, userId: 'userId');

// first let's read current user's timeline feed and pick one activity
  final activities =
      await clientWithSecret.flatFeed('user', '1').getActivities();

// then let's add a like reaction to that activity
  final otherLike = await clientWithSecret.reactions
      .add('like', activities.first.id!, userId: 'userId');

// retrieve all kind of reactions for an activity
  await clientWithSecret.reactions.filter(
      LookupAttribute.activityId, '5de5e4ba-add2-11eb-8529-0242ac130003');

// retrieve first 10 likes for an activity
  await clientWithSecret.reactions.filter(
      LookupAttribute.activityId, '5de5e4ba-add2-11eb-8529-0242ac130003',
      kind: 'like', limit: 10);

// retrieve the next 10 likes using the id_lt param
  await clientWithSecret.reactions.filter(
    LookupAttribute.activityId,
    '5de5e4ba-add2-11eb-8529-0242ac130003',
    kind: 'like',
    filter: Filter().idLessThan('e561de8f-00f1-11e4-b400-0cc47a024be0'),
  );

  // await clientWithSecret.reactions
  //     .update(comment.id!, data: {'text': 'love it!'});

// read bob's timeline and include most recent reactions to all activities and their total count
  await clientWithSecret.flatFeed('timeline', 'bob').getEnrichedActivities(
        flags: EnrichmentFlags().withRecentReactions().withReactionCounts(),
      );

// read bob's timeline and include most recent reactions to all activities and her own reactions
  await clientWithSecret.flatFeed('timeline', 'bob').getEnrichedActivities(
        flags: EnrichmentFlags().withRecentReactions().withReactionCounts(),
      );

// adds a comment reaction to the activity and notifies Thierry's notification feed
  await clientWithSecret.reactions.add(
      'comment', '5de5e4ba-add2-11eb-8529-0242ac130003',
      data: {'text': "@thierry great post!"},
      userId: 'userId',
      targetFeeds: [FeedId.id('notification:thierry')]);

  // adds a like to the previously created comment
  await clientWithSecret.reactions
      .addChild('like', comment.id!, userId: 'userId');
  await clientWithSecret.reactions.delete(comment.id!);
//Adding Collections
  // await client.collections.add(
  //   'food',
  //   {'name': 'Cheese Burger', 'rating': '4 stars'},
  //   entryId: 'cheese-burger',
  // );//will throw an error if entry-id already exists

// if you don't have an id on your side, just use null as the ID and Stream will generate a unique ID
  final entry = await clientWithSecret.collections
      .add('food', {'name': 'Cheese Burger', 'rating': '4 stars'});
  await clientWithSecret.collections.get('food', entry.id!);
  await clientWithSecret.collections.update(
      entry.copyWith(data: {'name': 'Cheese Burger', 'rating': '1 star'}));
  await clientWithSecret.collections.delete('food', entry.id!);

  // first we add our object to the food collection
  final cheeseBurger = await clientWithSecret.collections.add('food', {
    'name': 'Cheese Burger',
    'ingredients': ['cheese', 'burger', 'bread', 'lettuce', 'tomato'],
  });

// the object returned by .add can be embedded directly inside of an activity
  await user1.addActivity(Activity(
    actor: createUserReference('userId'),
    verb: 'grill',
    object: cheeseBurger.ref,
  ));

// if we now read the feed, the activity we just added will include the entire full object
  await user1.getEnrichedActivities();

// we can then update the object and Stream will propagate the change to all activities
  await clientWithSecret.collections.update(cheeseBurger.copyWith(data: {
    'name': 'Amazing Cheese Burger',
    'ingredients': ['cheese', 'burger', 'bread', 'lettuce', 'tomato'],
  }));

  // First create a collection entry with upsert api
  await clientWithSecret.collections.upsert('food', [
    CollectionEntry(id: 'cheese-burger', data: {'name': 'Cheese Burger'}),
  ]);

// Then create a user
  await clientWithSecret.user('john-doe').getOrCreate({
    'name': 'John Doe',
    'occupation': 'Software Engineer',
    'gender': 'male',
  });

// Since we know their IDs we can create references to both without reading from APIs
  final cheeseBurgerRef =
      clientWithSecret.collections.entry('food', 'cheese-burger').ref;
  final johnDoeRef = clientWithSecret.user('john-doe').ref;

// And then add an activity with these references
  await clientWithSecret.flatFeed('user', 'john').addActivity(Activity(
        actor: johnDoeRef,
        verb: 'eat',
        object: cheeseBurgerRef,
      ));

  client = StreamFeedClient.connect(apiKey, token: frontendToken);
// ensure the user data is stored on Stream
  await client.setUser({
    'name': 'John Doe',
    'occupation': 'Software Engineer',
    'gender': 'male'
  });

  // create a new user, if the user already exist an error is returned
  // await client.user('john-doe').create({
  //   'name': 'John Doe',
  //   'occupation': 'Software Engineer',
  //   'gender': 'male'
  // });

// get or create a new user, if the user already exist the user is returned
  await client.user('john-doe').getOrCreate({
    'name': 'John Doe',
    'occupation': 'Software Engineer',
    'gender': 'male'
  });

//retrieving users
  await client.user('john-doe').get();

  await client.user('john-doe').update({
    'name': 'Jane Doe',
    'occupation': 'Software Engineer',
    'gender': 'female'
  });

  //removing users
  await client.user('john-doe').delete();

  // Read the personalized feed for a given user
  var params = {'user_id': 'john-doe', 'feed_slug': 'timeline'};

  // await clientWithSecret.personalization
  //     .get('personalized_feed', params: params);

//Our data science team will typically tell you which endpoint to use
  params = {
    'user_id': 'john-doe',
    'source_feed_slug': 'timeline',
    'target_feed_slug': 'user'
  };

  // await client.personalization
  //     .get('discovery_feed', params: params);
  final analytics = StreamAnalytics(apiKey, secret: secret);
  analytics.setUser(id: 'id', alias: 'alias');
  await analytics.trackEngagement(
    Engagement(
      // the label for the engagement, ie click, retweet etc.
      label: 'click',
      content: Content(
          // the ID of the content that the user clicked
          foreignId: FeedId.id('tweet:34349698')),
      // score between 0 and 100 indicating the importance of this event
      // IE. a like is typically a more significant indicator than a click
      score: 2,
      // (optional) the position in a list of activities
      position: 3,
      boost: 2,

      // (optional) the feed the user is looking at
      feedId: FeedId('user', 'thierry'),
      // (optional) the location in your app. ie email, profile page etc
      location: 'profile_page',
    ),
  );

  await analytics.trackImpression(
    Impression(
      feedId: FeedId('timeline', 'tom'),
      location: 'profile_page',
      contentList: [
        Content(
          data: const {
            'foreign_id': 'post:42',
            'actor': {'id': 'user:2353540'},
            'verb': 'share',
            'object': {'id': 'song:34349698'},
          },
          foreignId: FeedId.id('post:42'),
        )
      ],
    ),
  );

  const imageURI = 'test/assets/test_image.jpeg';

  // uploading an image from the filesystem
  final imageUrl = await client.images.upload(AttachmentFile(path: imageURI));

  await client.images.getCropped(
    imageUrl!,
    const Crop(50, 50),
  );

  await client.images.getResized(
    imageUrl,
    const Resize(50, 50),
  );

// deleting an image using the url returned by the APIs
  await client.images.delete(imageUrl);

  const fileURI = 'test/assets/example.pdf';
  // uploading a file from the filesystem
  final fileUrl = await client.files.upload(AttachmentFile(path: fileURI));

// deleting a file using the url returned by the APIs
  await client.files.delete(fileUrl!);

  final preview = await client.og('http://www.imdb.com/title/tt0117500/');
} 

Download Details:

Author: GetStream

Source Code: https://github.com/GetStream/stream-feed-flutter

#flutter #stream