Merge remote-tracking branch 'origin/develop' into feat/localization

# Conflicts:
#	packages/stream_chat_flutter/example/lib/main.dart
#	packages/stream_chat_flutter/example/pubspec.yaml
#	packages/stream_chat_flutter/lib/src/channel_bottom_sheet.dart
#	packages/stream_chat_flutter/lib/src/channel_list_view.dart
#	packages/stream_chat_flutter/lib/src/gallery_footer.dart
#	packages/stream_chat_flutter/lib/src/message_input.dart
#	packages/stream_chat_flutter/lib/src/message_list_view.dart
#	packages/stream_chat_flutter/lib/src/user_item.dart
This commit is contained in:
xsahil03x
2021-07-19 12:49:07 +05:30
188 changed files with 6663 additions and 3145 deletions
+20
View File
@@ -0,0 +1,20 @@
name: docusaurus
on:
push:
branches:
- master
- develop
paths:
- docusaurus/**
jobs:
push_docusaurus:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: push
uses: GetStream/push-stream-chat-docusaurus-action@main
with:
target-branch: ${{ github.ref == 'refs/heads/master' && 'production' || 'staging' }}
env:
DOCUSAURUS_GH_TOKEN: ${{ secrets.DOCUSAURUS_GH_TOKEN }}
@@ -105,7 +105,7 @@ jobs:
uses: VeryGoodOpenSource/[email protected]
with:
path: packages/stream_chat/coverage/lcov.info
min_coverage: 40
min_coverage: 80
- name: "Stream Chat Persistence Coverage Check"
uses: VeryGoodOpenSource/[email protected]
with:
@@ -120,4 +120,4 @@ jobs:
uses: VeryGoodOpenSource/[email protected]
with:
path: packages/stream_chat_flutter/coverage/lcov.info
min_coverage: 35
min_coverage: 67
+139 -32
View File
@@ -22,7 +22,7 @@ You can include the output of `flutter doctor --verbose` when filing an issue.
Stream's Flutter code is kept in a single mono-repository consisting of multiple packages. Source code for each package can be found under the top-level `/packages` directory.
![https://s3.us-west-2.amazonaws.com/secure.notion-static.com/b1a202d3-44c8-4d1a-a5c3-583e7a3c4106/Screen_Shot_2021-03-31_at_4.13.52_PM.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075243Z&X-Amz-Expires=86400&X-Amz-Signature=0582138dc957b784d4d505f6591cd3566cede2137fdf48ac546768822f344cab&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Screen_Shot_2021-03-31_at_4.13.52_PM.png%22](https://s3.us-west-2.amazonaws.com/secure.notion-static.com/b1a202d3-44c8-4d1a-a5c3-583e7a3c4106/Screen_Shot_2021-03-31_at_4.13.52_PM.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075243Z&X-Amz-Expires=86400&X-Amz-Signature=0582138dc957b784d4d505f6591cd3566cede2137fdf48ac546768822f344cab&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Screen_Shot_2021-03-31_at_4.13.52_PM.png%22)
<img width="1436" alt="Screen_Shot_2021-03-31_at_4 13 52_PM" src="https://user-images.githubusercontent.com/20601437/124240912-8791a080-db1b-11eb-9467-b00e9d14b1ca.png">
### Project Structure 🧱
@@ -88,11 +88,11 @@ Before filing bugs, take a look at our existing backlog. For common bugs, there
To quickly narrow down the amount of tickets on Github, try filtering based on the label that best suites the bug.
![https://s3.us-west-2.amazonaws.com/secure.notion-static.com/fbdb4e20-4914-416c-831d-6dee7d724501/Screen_Shot_2021-04-14_at_10.55.00_AM.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075432Z&X-Amz-Expires=86400&X-Amz-Signature=e8c5a2a16de7e059bd1ee55f3d76736823e3fe0583bbb4ab8dd16bb9f792e33c&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Screen_Shot_2021-04-14_at_10.55.00_AM.png%22](https://s3.us-west-2.amazonaws.com/secure.notion-static.com/fbdb4e20-4914-416c-831d-6dee7d724501/Screen_Shot_2021-04-14_at_10.55.00_AM.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075432Z&X-Amz-Expires=86400&X-Amz-Signature=e8c5a2a16de7e059bd1ee55f3d76736823e3fe0583bbb4ab8dd16bb9f792e33c&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Screen_Shot_2021-04-14_at_10.55.00_AM.png%22)
![image](https://user-images.githubusercontent.com/20601437/124240983-9d9f6100-db1b-11eb-952f-3c0cc60a910e.png)
Didn't find an existing issue? Go ahead and file a new bug using one of our pre-made issue templates.
![https://s3.us-west-2.amazonaws.com/secure.notion-static.com/02977615-c003-4b06-9d65-093ad95e6161/Screen_Shot_2021-04-14_at_10.56.17_AM.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075509Z&X-Amz-Expires=86400&X-Amz-Signature=1153332c6bb3e54f69045c2ff47b3464039bbd4a8bd8a504ed7b2629eadb6ef8&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Screen_Shot_2021-04-14_at_10.56.17_AM.png%22](https://s3.us-west-2.amazonaws.com/secure.notion-static.com/02977615-c003-4b06-9d65-093ad95e6161/Screen_Shot_2021-04-14_at_10.56.17_AM.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075509Z&X-Amz-Expires=86400&X-Amz-Signature=1153332c6bb3e54f69045c2ff47b3464039bbd4a8bd8a504ed7b2629eadb6ef8&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Screen_Shot_2021-04-14_at_10.56.17_AM.png%22)
![image](https://user-images.githubusercontent.com/20601437/124241045-aee86d80-db1b-11eb-89eb-f4189019ac3e.png)
Be sure to provide as much information as possible when filing bug reports. A good issue should have steps to reproduce and information on your development environment and expected behavior.
@@ -108,7 +108,7 @@ To file a feature request, select the "Discussions" tab on our GitHub repo or [v
Screenshots, sketches, and sample code are all welcomed!
![https://s3.us-west-2.amazonaws.com/secure.notion-static.com/4525f80a-e96f-4e05-8155-b4982df46c25/Screen_Shot_2021-04-14_at_11.08.48_AM.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075528Z&X-Amz-Expires=86400&X-Amz-Signature=9bfbd045d99d3f3297cfd5d2885da85324d0f2da3ad272376680ca6913b050d5&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Screen_Shot_2021-04-14_at_11.08.48_AM.png%22](https://s3.us-west-2.amazonaws.com/secure.notion-static.com/4525f80a-e96f-4e05-8155-b4982df46c25/Screen_Shot_2021-04-14_at_11.08.48_AM.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075528Z&X-Amz-Expires=86400&X-Amz-Signature=9bfbd045d99d3f3297cfd5d2885da85324d0f2da3ad272376680ca6913b050d5&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Screen_Shot_2021-04-14_at_11.08.48_AM.png%22)
![image](https://user-images.githubusercontent.com/20601437/124241092-bc055c80-db1b-11eb-9205-7e3d7c157af1.png)
Here are some common questions to answer when filing a feature request:
@@ -130,7 +130,7 @@ Add any other context or screenshots about the feature request here.
## Pull Request 🎉
![https://s3.us-west-2.amazonaws.com/secure.notion-static.com/fe7dad03-6edc-4ef4-8c3b-303853cd8aec/its-coding-time.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075543Z&X-Amz-Expires=86400&X-Amz-Signature=d49c488e4ec8dd15e10660be6b6fa13a49991771ebed93f395e251ae5a198150&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22its-coding-time.jpeg%22](https://s3.us-west-2.amazonaws.com/secure.notion-static.com/fe7dad03-6edc-4ef4-8c3b-303853cd8aec/its-coding-time.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075543Z&X-Amz-Expires=86400&X-Amz-Signature=d49c488e4ec8dd15e10660be6b6fa13a49991771ebed93f395e251ae5a198150&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22its-coding-time.jpeg%22)
![image](https://user-images.githubusercontent.com/20601437/124241146-c7f11e80-db1b-11eb-9588-d9f578ec004a.png)
Thank you for taking the time to submit a patch and contribute to our codebase. You rock!
@@ -177,52 +177,159 @@ Develop is merged into master after the team performs various automated and QA t
# Styleguides 💅
![https://s3.us-west-2.amazonaws.com/secure.notion-static.com/c980959d-4ed2-4b93-97fc-016a9ded3f0f/d1d0f6c27141606521bfa6171bfe2a84.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075603Z&X-Amz-Expires=86400&X-Amz-Signature=94248827f187e1c2628ae1b0ff1aed1475325e2699acc89eb64145a2eb6d6968&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22d1d0f6c27141606521bfa6171bfe2a84.png%22](https://s3.us-west-2.amazonaws.com/secure.notion-static.com/c980959d-4ed2-4b93-97fc-016a9ded3f0f/d1d0f6c27141606521bfa6171bfe2a84.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20210423%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210423T075603Z&X-Amz-Expires=86400&X-Amz-Signature=94248827f187e1c2628ae1b0ff1aed1475325e2699acc89eb64145a2eb6d6968&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22d1d0f6c27141606521bfa6171bfe2a84.png%22)
![image](https://user-images.githubusercontent.com/20601437/124241186-d17a8680-db1b-11eb-9a21-3df305674ca9.png)
We use style guides and lint checks to keep our code consistent and maintain best practices. Our team uses Dart's built-in analyzer for linting and enforcing code styles. The full list of analyzer rules can be found below.
## Dart lint rules 📖
```jsx
include: package:pedantic/analysis_options.yaml
```yaml
analyzer:
enable-experiment:
- extension-methods
exclude:
- lib/**/*.g.dart
- example/**
- packages/*/lib/**/*.g.dart
- packages/*/example/**
- packages/*/lib/src/emoji
- packages/*/lib/**/*.freezed.dart
- packages/*/test/**
linter:
rules:
# these rules are documented on and in the same order as
# the Dart Lint rules page to make maintenance easier
# https://github.com/dart-lang/linter/blob/master/example/all.yaml
- always_use_package_imports
- avoid_empty_else
- avoid_init_to_null
- avoid_return_types_on_setters
- avoid_web_libraries_in_flutter
- await_only_futures
- camel_case_types
- avoid_relative_lib_imports
- avoid_slow_async_io
- avoid_types_as_parameter_names
- cancel_subscriptions
- close_sinks
- control_flow_in_finally
- empty_constructor_bodies
- empty_statements
- hash_and_equals
- implementation_imports
- library_names
- non_constant_identifier_names
- package_names
- package_prefixed_library_names
- prefer_is_not_empty
- public_member_api_docs
- slash_for_doc_comments
- sort_constructors_first
- sort_unnamed_constructors_first
- invariant_booleans
- iterable_contains_unrelated_type
- list_remove_unrelated_type
- literal_only_boolean_expressions
- no_adjacent_strings_in_list
- no_duplicate_case_values
- no_logic_in_create_state
- prefer_void_to_null
- test_types_in_equals
- throw_in_finally
- type_init_formals
- unnecessary_brace_in_string_interps
- unnecessary_getters_setters
- unnecessary_statements
- unrelated_type_equality_checks
- omit_local_variable_types
- use_key_in_widget_constructors
- valid_regexps
- always_declare_return_types
- always_require_non_null_named_parameters
- annotate_overrides
- avoid_bool_literals_in_conditional_expressions
- avoid_catching_errors
- avoid_init_to_null
- avoid_null_checks_in_equality_operators
- avoid_positional_boolean_parameters
- avoid_private_typedef_functions
- avoid_redundant_argument_values
- avoid_return_types_on_setters
- avoid_returning_null_for_void
- avoid_shadowing_type_parameters
- avoid_single_cascade_in_expression_statements
- avoid_unnecessary_containers
- avoid_unused_constructor_parameters
- await_only_futures
- camel_case_extensions
- camel_case_types
- cascade_invocations
- constant_identifier_names
- curly_braces_in_flow_control_structures
- directives_ordering
- empty_catches
- empty_constructor_bodies
- exhaustive_cases
- file_names
- implementation_imports
- join_return_with_assignment
- leading_newlines_in_multiline_strings
- library_names
- library_prefixes
- lines_longer_than_80_chars
- missing_whitespace_between_adjacent_strings
- non_constant_identifier_names
- null_closures
- one_member_abstracts
- only_throw_errors
- package_api_docs
- package_prefixed_library_names
- parameter_assignments
- prefer_adjacent_string_concatenation
- prefer_asserts_in_initializer_lists
- prefer_asserts_with_message
- prefer_collection_literals
- prefer_conditional_assignment
- prefer_const_constructors
- prefer_const_constructors_in_immutables
- prefer_const_declarations
- prefer_const_literals_to_create_immutables
- prefer_constructors_over_static_methods
- prefer_contains
- prefer_equal_for_default_values
- prefer_expression_function_bodies
- prefer_final_fields
- prefer_final_in_for_each
- prefer_final_locals
- prefer_function_declarations_over_variables
- prefer_generic_function_type_aliases
- prefer_if_elements_to_conditional_expressions
- prefer_if_null_operators
- prefer_initializing_formals
- prefer_inlined_adds
- prefer_int_literals
- prefer_interpolation_to_compose_strings
- prefer_is_empty
- prefer_is_not_empty
- prefer_is_not_operator
- prefer_null_aware_operators
- prefer_single_quotes
- prefer_spread_collections
- prefer_typing_uninitialized_variables
- provide_deprecation_message
- public_member_api_docs
- recursive_getters
- sized_box_for_whitespace
- slash_for_doc_comments
- sort_child_properties_last
- sort_constructors_first
- sort_unnamed_constructors_first
- type_annotate_public_apis
- type_init_formals
- unnecessary_await_in_return
- unnecessary_brace_in_string_interps
- unnecessary_const
- unnecessary_getters_setters
- unnecessary_lambdas
- unnecessary_new
- unnecessary_null_aware_assignments
- unnecessary_null_in_if_null_operators
- unnecessary_nullable_for_final_variable_declarations
- unnecessary_parenthesis
- unnecessary_raw_strings
- unnecessary_string_escapes
- unnecessary_string_interpolations
- unnecessary_this
- use_is_even_rather_than_modulo
- use_late_for_private_fields_and_variables
- use_rethrow_when_possible
- use_setters_to_change_properties
- use_to_and_as_if_applicable
- package_names
- sort_pub_dependencies
- cast_nullable_to_non_nullable
- unnecessary_null_checks
- tighten_type_of_initializing_formals
- null_check_on_nullable_type_parameter
```
-2
View File
@@ -1,10 +1,8 @@
analyzer:
exclude:
- packages/*/lib/**/*.g.dart
- packages/*/example/**
- packages/*/lib/src/emoji
- packages/*/lib/**/*.freezed.dart
- packages/*/test/**
linter:
rules:
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 876 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 459 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 564 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1,4 @@
{
"label": "Introduction",
"position": 1
}
@@ -0,0 +1,55 @@
---
id: choose_package
sidebar_position: 2
title: Choosing The Right Flutter Package
---
### Why the SDK is split into different packages
Different applications need different levels of customization and integration with the Stream Chat SDK.
To do this, the Flutter SDK is split into three different packages which build upon the last and give
varying levels of control to the developer. The higher level packages offer better compatibility out of the
box while the lower level SDKs offer fine grained control. There is also a separate package for persistence
which allows you persist data locally which works with all packages.
### How do I choose?
#### The case for stream_chat_flutter
For the quickest way to integrate Stream Chat with your app, the UI SDK (`stream_chat_flutter`) is the
way to go. `stream_chat_flutter` contains prebuilt components that manage most operations like data
fetching, pagination, sending a message, and more. This ensures you have a nearly out-of-the-box
experience adding chat to your applications. It is also possible to use this in conjunction with
lower level operations of the SDK to get the best of both worlds.
:::note
The package allows customization of components to a large extent making it easy to tweak the theme
to match your app colors and such. If you require any additional feature or customization, feel free
to request this through our support channels.
:::
<b>Summary:</b>
For the quickest and easiest way to add Chat to your app with prebuilt UI components, use stream_chat_flutter
#### The case for stream_chat_flutter_core
If your application involves UI that does not fit in with the stream_chat_flutter components, stream_chat_flutter_core
strips away the UI associated with the components and provides the data fetching and manipulation
capabilities while supplying builders for UI. This allows you to implement your own UI and themes
completely independently while not worrying about writing functions for data and pagination.
<b>Summary:</b>
For implementing your own custom UI while not having to worry about lower level API calls, use stream_chat_flutter_core.
#### The case for stream_chat
The stream_chat package is the Low-level Client (LLC) of Stream Chat in Flutter. This package wraps
the underlying functionality of Stream Chat and allows the most customization in terms of UI, data,
and architecture.
<b>Summary:</b>
For the most control over the SDK and dealing with low level calls to the API, use stream_chat.
@@ -0,0 +1,71 @@
---
slug: /
id: introduction
sidebar_position: 1
title: About The Flutter SDK
---
Exploring The Basics Of Stream Chat
![](../assets/sdk_title.png)
Stream Chat is a service that helps you easily build a full chat experience in your Flutter (and more) apps.
This section of the documentation focuses on our Flutter SDK which helps you easily
ship high quality messaging experiences in apps and programs built with the [Flutter toolkit made
by Google](https://flutter.dev).
The Stream Chat Flutter SDK comprises of four different packages to choose from ranging from ones
giving you complete control to ones that give you a rich out-of-the-box chat experience.
The packages that make up the Stream Chat SDK are:
1. <b>Low Level Client (stream_chat)</b>: a pure Dart package that can be used on any Dart project.
It provides a low-level client to access the Stream Chat service.
2. <b>Core (stream_chat_flutter_core)</b>: provides business logic to fetch common things required
for integrating Stream Chat into your application.
The core package allows more customisation and hence provides business logic but no UI components.
3. <b>UI (stream_chat_flutter)</b>: this library includes both a low-level chat SDK and a set of
reusable and customisable UI components.
4. <b>Persistence (stream_chat_persistence)</b>: provides a persistence client for fetching and
saving chat data locally.
We recommend building prototypes using the full UI package since it contains UI widgets already
integrated with Stream's API. [stream_chat_flutter](https://pub.dev/packages/stream_chat_flutter)
is the fastest way to get up and running using Stream chat in your app.
The Flutter SDK enables you to build any type of chat or messaging experience for Android, iOS, Web
and Desktop.
If you're building a very custom UI and would prefer a more lean package,
our [core package](https://pub.dev/packages/stream_chat_flutter) will be suited to this use case. Core allows you to build custom,
expressive UIs while retaining the benefits of our full Flutter SDK.
APIs for accessing and controlling users, sending messages, etc are seamlessly integrated into
this package and accessible via providers and builders.
Before going into the docs, let's take a small detour to look at how the elements of Stream Chat are structured.
There are two core elements in chat, <b>Users and Channels.</b>
Channels are groups of one or more users that can message each other.
In an app, you need to have a user connected to query channels.
There is no specific distinction between a chat between two people and a group chat,
but there is a way to create a unique chat between a certain number of people by creating a <b>distinct</b> channel.
![](../assets/chat_basics.png)
In essence, a normal two-person chat would be a <b>distinct channel</b> created with two members (you cannot add or delete members in this channel), whereas a group created with two people would simply be a <b>non distinct channel</b> (possible to add or remove members).
Note: It is also possible to add more than two people in a distinct channel which retains the same add/removal properties and resembles the Slack DMs where you can DM one or more people as well.
In summary, if you were creating a Whatsapp-like app, the first screen would be a <b>list of channels</b> - which on opening would show a <b>list of messages</b> that were sent by the users in the Channel.
While this is a simplistic overview of the service, the Flutter SDK handles the UI and more time consuming things (media upload, offline storage, theming, etc.) for you.
Before reading the docs, consider trying our [online API tour](https://getstream.io/chat/get_started/),
it is a nice way to learn how the API works.
It's in-browser so Javascript-based but the ideas are pretty much the same as Dart.
You may also like to look at the [Flutter tutorial](https://getstream.io/chat/flutter/tutorial/)
which focuses on using the UI package to get Stream Chat integrated into a Flutter app.
Further sections break down each individual packages and explain several common operations.
@@ -0,0 +1,4 @@
{
"label": "Guides",
"position": 2
}
@@ -0,0 +1,260 @@
---
id: adding_custom_attachments
sidebar_position: 4
title: Adding Custom Attachments
---
Adding Your Own Types Of Attachments To A Message
### Introduction
Stream Chat supports attachment types like images, video and files by default. You can also add your
own types of attachments through the SDK such as location, audio, etc.
This involves doing three things:
1) Rendering the attachment thumbnail in the `MessageInput`
2) Sending a message with the custom attachment
3) Rendering the custom message attachment
To do this, let's check out an example to add location sharing to Stream Chat.
### Location Sharing
Let's build an example of location sharing option in the app:
![](../assets/location_sharing_example.jpg)
* Show a "Share Location" button next to MessageInput Textfield.
* When the user presses this button, it should fetch the current location coordinates of the user, and send a message on the channel as follows:
```dart
Message(
text: 'This is my location',
attachments: [
Attachment(
uploadState: UploadState.success(),
type: 'location',
extraData: {
'latitude': 'fetched_latitude',
'longitude': 'fetched_longitude',
},
),
],
)
```
For our example, we are going to use [geolocator](https://pub.dev/packages/geolocator) library.
Please check their [setup instructions](https://pub.dev/packages/geolocator) on their docs.
NOTE: If you are testing on iOS simulator, you will need to set some dummy coordinates, as mentioned [here](https://stackoverflow.com/a/31238119/7489541).
Also don't forget to enable "location update" capability in background mode, from XCode.
On the receiver end, `location` type attachment should be rendered in map view, in the `MessageListView`.
We are going to use [Google Static Maps API](https://developers.google.com/maps/documentation/maps-static/overview) to render the map in the message.
You can use other libraries as well such as [google_maps_flutter](https://pub.dev/packages/google_maps_flutter).
First, we add a button which when clicked fetches and shares location into the `MessageInput`:
```dart
MessageInput(
actions: [
InkWell(
child: Icon(
Icons.location_on,
size: 20.0,
color: StreamChatTheme.of(context).colorTheme.grey,
),
onTap: () {
var channel = StreamChannel.of(context).channel;
var user = StreamChat.of(context).user;
_determinePosition().then((value) {
channel.sendMessage(
Message(
text: 'This is my location',
attachments: [
Attachment(
uploadState: UploadState.success(),
type: 'location',
extraData: {
'latitude': value.latitude.toString(),
'longitude': value.longitude.toString(),
},
),
],
),
);
}).catchError((err) {
print('Error getting location!');
});
},
),
],
),
Future<Position> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.deniedForever) {
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
if (permission == LocationPermission.denied) {
return Future.error(
'Location permissions are denied');
}
}
return await Geolocator.getCurrentPosition();
}
```
Next, we build the Static Maps URL (Add your API key before using the code snippet):
```dart
String _buildMapAttachment(String lat, String long) {
var baseURL = 'https://maps.googleapis.com/maps/api/staticmap?';
var url = Uri(
scheme: 'https',
host: 'maps.googleapis.com',
port: 443,
path: '/maps/api/staticmap',
queryParameters: {
'center': '${lat},${long}',
'zoom': '15',
'size': '600x300',
'maptype': 'roadmap',
'key': 'YOUR_API_KEY',
'markers': 'color:red|${lat},${long}'
});
return url.toString();
}
```
And then modify the MessageListView and tell it how to build a location attachment:
```dart
MessageListView(
customAttachmentBuilders: {
'location': (context, message, attachments) {
var attachmentWidget = Image.network(
_buildMapAttachment(
attachments[0].extraData['latitude'],
attachments[0].extraData['longitude'],
),
);
return wrapAttachmentWidget(context, attachmentWidget, null, true, BorderRadius.circular(8.0));
}
},
),
```
This gives us the final location attachment:
![](../assets/location_sharing_example_message.jpg)
Additionally, you can also add a thumbnail if a message has a location attachment (unlike in this case, where we sent the message directly).
To do this, we will:
1) Add an attachment instead of sending a message
2) Customize the `MessageInput`
First, we add the attachment when the location button is clicked:
```dart
GlobalKey<MessageInputState> _messageInputKey = GlobalKey();
MessageInput(
key: _messageInputKey,
actions: [
InkWell(
child: Icon(
Icons.location_on,
size: 20.0,
color: StreamChatTheme.of(context).colorTheme.grey,
),
onTap: () {
_determinePosition().then((value) {
_messageInputKey.currentState.addAttachment(
Attachment(
uploadState: UploadState.success(),
type: 'location',
extraData: {
'latitude': value.latitude.toString(),
'longitude': value.longitude.toString(),
},
),
);
}).catchError((err) {
print('Error getting location!');
});
},
),
],
),
```
After this, we can build the thumbnail:
```dart
MessageInput(
key: _messageInputKey,
actions: [
InkWell(
child: Icon(
Icons.location_on,
size: 20.0,
color: StreamChatTheme.of(context).colorTheme.grey,
),
onTap: () {
_determinePosition().then((value) {
_messageInputKey.currentState.addAttachment(
Attachment(
uploadState: UploadState.success(),
type: 'location',
extraData: {
'latitude': value.latitude.toString(),
'longitude': value.longitude.toString(),
},
),
);
}).catchError((err) {
print('Error getting location!');
});
},
),
],
attachmentThumbnailBuilders: {
'location': (context, attachment) {
return Image.network(
_buildMapAttachment(
attachment.extraData['latitude'],
attachment.extraData['longitude'],
),
);
},
},
),
```
And we can see the thumbnails in the MessageInput:
![](../assets/location_sharing_example_message_thumbnail.jpg)
@@ -0,0 +1,6 @@
---
id: local_data_persistence
sidebar_position: 2
title: Adding Local Data Persistence
---
@@ -0,0 +1,234 @@
---
id: adding_push_notifications
sidebar_position: 3
title: Adding Push Notifications
---
Adding Push Notifications To Your Application
### Introduction
Push notifications are a core part of the experience for a messaging app. Users often need to be notified
of new messages and old notifications sometimes need to be updated silently as well.
This guide details how to add push notifications to your app.
Make sure to check [this section](https://getstream.io/chat/docs/flutter-dart/push_introduction/?language=dart) of the docs to read about the push delivery logic.
### Setup FCM
To integrate push notifications in your Flutter app you need to use the package [firebase_messaging](https://pub.dev/packages/firebase_messaging).
Follow the [Firebase documentation](https://firebase.flutter.dev/docs/messaging/overview/) to know how to set up the plugin for both Android and iOS.
Once that's done FCM should be able to send push notifications to your devices.
### Integration with Stream
#### Step 1
From the [Firebase Console](https://console.firebase.google.com/), select the project your app belongs to.
#### Step 2
Click on the gear icon next to `Project Overview` and navigate to **Project settings**
![](../assets/firebase_project_settings.jpeg)
#### Step 3
Navigate to the `Cloud Messaging` tab
#### Step 4
Under `Project Credentials`, locate the `Server key` and copy it
![](../assets/server_key.png)
#### Step 5
Upload the `Server Key` in your chat dashboard
![](../assets/dashboard_firebase_enable.jpeg)
![](../assets/dashboard_firebase_key.jpeg)
:::note
We are setting up the Android section, but this will work for both Android and iOS if you're using Firebase for both of them!
:::
#### Step 6
Save your push notification settings changes
![](../assets/dashboard_save_changes.jpeg)
**OR**
Upload the `Server Key` via API call using a backend SDK
```js
await client.updateAppSettings({
firebase_config: {
server_key: 'server_key',
notification_template: `{"message":{"notification":{"title":"New messages","body":"You have {{ unread_count }} new message(s) from {{ sender.name }}"},"android":{"ttl":"86400s","notification":{"click_action":"OPEN_ACTIVITY_1"}}}}`,
data_template: `{"sender":"{{ sender.id }}","channel":{"type": "{{ channel.type }}","id":"{{ channel.id }}"},"message":"{{ message.id }}"}`
},
});
```
### Registering a device at Stream Backend
Once you configure Firebase server key and set it up on Stream dashboard a device that is supposed to receive push notifications needs to be registered at Stream backend. This is usually done by listening for Firebase device token updates and passing them to the backend as follows:
```dart
firebaseMessaging.onTokenRefresh.listen((token) {
client.addDevice(token, PushProvider.firebase);
});
```
### Possible issues
We only send push notifications when the user doesn't have any active websocket connection (which is established when you call `client.connectUser`). If you set the [onBackgroundEventReceived](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/StreamChat/onBackgroundEventReceived.html) property of the StreamChat widget, when your app goes to background, your device will keep the ws connection alive for 1 minute, and so within this period, you won't receive any push notification.
Make sure to read the [general push docs](https://getstream.io/chat/docs/flutter-dart/push_introduction/?language=dart) in order to avoid known gotchas that may make your relationship with notifications go bad 😢
### Testing if Push Notifications are Setup Correctly
If you're not sure if you've set up push notifications correctly (e.g. you don't always receive them, they work unreliably), you can follow these steps to make sure your config is correct and working:
1. Clone our repo for push testing git clone [email protected]:GetStream/chat-push-test.git
2. `cd flutter`
3. In folder run `flutter pub get`
4. Input your api key and secret in `lib/main.dart`
5. Change the bundle identifier/application ID and development team/user so you can run the app in your device (**do not** run on iOS simulator, Android emulator is fine)
6. Add your `google-services.json/GoogleService-Info.plist`
7. Run the app
8. Accept push notification permission (iOS only)
9. Tap on `Device ID` and copy it
10. Send the app to background
11. After configuring [stream-cli](https://github.com/GetStream/stream-cli) paste the following command on command line using your user ID
```shell
stream chat:push:test -u <USER-ID>
```
You should get a test push notification
### App in the background but still connected
The [StreamChat](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/StreamChat-class.html) widget lets you define a [onBackgroundEventReceived](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/StreamChat/onBackgroundEventReceived.html) handler in order to handle events while the app is in the background, but the client is still connected.
This is useful because it lets you keep the connection alive in cases in which the app goes in the background just for some seconds (eg: multitasking, picking pictures from the gallery...)
You can even customize the [backgroundKeepAlive](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/StreamChat/backgroundKeepAlive.html) duration.
In order to show notifications in such a case we suggest using the package [flutter_local_notifications](https://pub.dev/packages/flutter_local_notifications); follow the package guide to successfully set up the plugin.
Once that's done you should set the [onBackgroundEventReceived](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/StreamChat/onBackgroundEventReceived.html); here is an example:
```dart
...
StreamChat(
client: client,
onBackgroundEventReceived: (e) {
final currentUserId = client.state.user.id;
if (![
EventType.messageNew,
EventType.notificationMessageNew,
].contains(event.type) ||
event.user.id == currentUserId) {
return;
}
if (event.message == null) return;
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
final initializationSettingsAndroid =
AndroidInitializationSettings('launch_background');
final initializationSettingsIOS = IOSInitializationSettings();
final initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
await flutterLocalNotificationsPlugin.show(
event.message.id.hashCode,
event.message.user.name,
event.message.text,
NotificationDetails(
android: AndroidNotificationDetails(
'message channel',
'Message channel',
'Channel used for showing messages',
priority: Priority.high,
importance: Importance.high,
),
iOS: IOSNotificationDetails(),
),
);
},
child: ....
);
...
```
As you can see we generate a local notification whenever a message.new or notification.message_new event is received.
:::note
Using `flutter_local_notifications` is a great way to implement notifications while the is in foreground too! You can generate a local notification listening to events using the method `streamChatClient.on()` and react to the events you want.
:::
### Saving notification messages to the offline storage
You may want to save received messages when you receive them via a notification so that later on when you open the app they're already there.
To do this we need to update the push notification data payload at Stream Dashboard and clear the notification one:
```json
{
"message_id": "{{ message.id }}",
"channel_id": "{{ channel.id }}",
"channel_type": "{{ channel.type }}"
}
```
Then we need to integrate the package [stream_chat_persistence](https://pub.dev/packages/stream_chat_persistence) in our app that exports a persistence client, learn [here](https://pub.dev/packages/stream_chat_persistence#usage) how to set it up.
Then during the call `firebaseMessaging.configure(...)` we need to set the `onBackgroundMessage` parameter using a TOP-LEVEL or STATIC function to handle background messages; here is an example:
```dart
Future<dynamic> myBackgroundMessageHandler(message) async {
if (message.containsKey('data')) {
final data = message['data'];
final messageId = data['message_id'];
final channelId = data['channel_id'];
final channelType = data['channel_type'];
final cid = '$channelType:$channelId';
final client = StreamChatClient(apiKey);
final persistenceClient = StreamChatPersistenceClient();
await persistenceClient.connect(userId);
final message = await client.getMessage(messageId).then((res) => res.message);
await persistenceClient.updateMessages(cid, [message]);
persistenceClient.disconnect();
/// This can be done using the package flutter_local_notifications as we did before 👆
_showLocalNotification();
}
}
```
@@ -0,0 +1,5 @@
---
id: introduction
sidebar_position: 1
title: Introduction
---
@@ -0,0 +1,298 @@
---
id: mig_guide_2_0
sidebar_position: 5
title: Migrating to 2.0 (Null-safety)
---
A Migration Guide For Switching To v2.0 Of The Flutter SDK
### Overview
v2.0 of the Stream Chat Flutter SDK brings along several changes - primarily making the SDK null-safe.
Null safety allows your apps to run faster, with fewer errors, and with less code.
Check [this link](https://flutter.dev/docs/null-safety) for more about Null Safety in Flutter.
This guide is intended to enumerate and better explain the changes in the SDK.
The changes will be listed by package and a concise changelog will follow with more info.
### Changelog of `stream_chat_flutter`
#### 🛑️ Breaking Changes from 1.5.4
* Migrate this package to null safety
* Renamed `ChannelImage` to `ChannelAvatar`
* Updated `StreamChatThemeData.reactionIcons` to accept custom builder
* Renamed `ColorTheme` properties to reflect the purpose of the colors
* `ColorTheme.black` -> `ColorTheme.textHighEmphasis`
* `ColorTheme.grey` -> `ColorTheme.textLowEmphasis`
* `ColorTheme.greyGainsboro` -> `ColorTheme.disabled`
* `ColorTheme.greyWhisper` -> `ColorTheme.borders`
* `ColorTheme.whiteSmoke` -> `ColorTheme.inputBg`
* `ColorTheme.whiteSnow` -> `ColorTheme.appBg`
* `ColorTheme.white` -> `ColorTheme.barsBg`
* `ColorTheme.blueAlice` -> `ColorTheme.linkBg`
* `ColorTheme.accentBlue` -> `ColorTheme.accentPrimary`
* `ColorTheme.accentRed` -> `ColorTheme.accentError`
* `ColorTheme.accentGreen` -> `ColorTheme.accentInfo`
* `ChannelListCore` options property is removed in favor of individual properties
* `options.state` -> `bool state`
* `options.watch` -> `bool watch`
* `options.presence` -> `bool presence`
* `UserListView` options property is removed in favor of individual properties
* `options.presence` -> `bool presence`
* Renamed `ImageHeader` to `GalleryHeader`
* Renamed `ImageFooter` to `GalleryFooter`
* `MessageBuilder` and `ParentMessageBuilder` signature is now
```
typedef MessageBuilder = Widget Function(
BuildContext,
MessageDetails,
List<Message>,
MessageWidget defaultMessageWidget,
);
```
The last parameter is the default `MessageWidget`
You can call `.copyWith` to customize just a subset of properties
#### ✅ Added
Added video compress options (frame and quality) to MessageInput
`TypingIndicator` now has a property called `parentId` to show typing indicator specific to threads
#493: add support for `MessageListView` header/footer
`MessageWidget` accepts a `userAvatarBuilder`
Added `pinMessage` ui support
Added `MessageListView.threadSeparatorBuilder` property
Added `MessageInput.onError` property to allow error handling
Added `GalleryHeader`/`GalleryFooter` theme classes
#### 🐞 Fixed
#483: Keyboard covers input text box when editing message
`Modals` are shown using the nearest `Navigator` to make using the SDK easier in a nested navigator use case
#484: messages don't update without a reload
`MessageListView` not rendering if the user is not a member of the channel
Fix `MessageInput` overflow when there are no actions
Minor fixes and improvements
### Migrating to 2.0 for `stream_chat_flutter`
:::note
If you are migrating your full Flutter project to null-safety, first make sure you follow the
instructions from the [official Null Safety migration guide](https://dart.dev/null-safety/migration-guide).
:::
To migrate to v2.0 for `stream_chat_flutter`, first change the version of the package to the latest
null-safe version.
```yaml
dependencies:
stream_chat_flutter: ^2.0.0
```
Upon doing this, all breaking changes from the package will take immediate effect. Here are steps to
remedy the issues:
1) Replace the offending class names with the revised class names
* `ChannelImage` -> `ChannelAvatar`
* `ImageHeader` -> `GalleryHeader`
* `ImageFooter` -> `GalleryFooter`
2) The new version comes with revised color names since the previous names do not suit light/dark mode
nomenclature. Make sure any old colors used from theme are changed over to the new theme color names:
* `ColorTheme.black` -> `ColorTheme.textHighEmphasis`
* `ColorTheme.grey` -> `ColorTheme.textLowEmphasis`
* `ColorTheme.greyGainsboro` -> `ColorTheme.disabled`
* `ColorTheme.greyWhisper` -> `ColorTheme.borders`
* `ColorTheme.whiteSmoke` -> `ColorTheme.inputBg`
* `ColorTheme.whiteSnow` -> `ColorTheme.appBg`
* `ColorTheme.white` -> `ColorTheme.barsBg`
* `ColorTheme.blueAlice` -> `ColorTheme.linkBg`
* `ColorTheme.accentBlue` -> `ColorTheme.accentPrimary`
* `ColorTheme.accentRed` -> `ColorTheme.accentError`
* `ColorTheme.accentGreen` -> `ColorTheme.accentInfo`
3) We decided to make messages easier to customize and now supply the default implementation of the
messages in the builder - so you can now customize a single parameter without having to redo the
entire implementation. Please reform your builders to take into account the new format:
```
typedef MessageBuilder = Widget Function(
BuildContext,
MessageDetails,
List<Message>,
MessageWidget defaultMessageWidget,
);
```
To tweak any of the default properties individually, you can use `defaultMessageWidget.copyWith()`.
### Changelog of `stream_chat_flutter_core`
#### 🛑️ Breaking Changes from 1.5.3
* Migrate this package to null safety
* `channelsBloc.queryChannels()`, `ChannelListCore` options param/property is removed in favor of individual params/properties
* `options.state` -> `bool state`
* `options.watch` -> `bool watch`
* `options.presence` -> `bool presence`
* `usersBloc.queryUsers()`, `UserListCore` options param/property is removed in favor of individual params/properties
* `options.presence` -> `bool presence`
#### ✅ Added
* Monitor connection using `connectivity_plus` package
#### 🐞 Fixed
* Minor fixes
* Performance improvements
### Migrating to 2.0 for `stream_chat_flutter_core`
:::note
If you are migrating your full Flutter project to null-safety, first make sure you follow the
instructions from the [official Null Safety migration guide](https://dart.dev/null-safety/migration-guide).
:::
To migrate to v2.0 for `stream_chat_flutter_core`, first change the version of the package to the latest
null-safe version.
```yaml
dependencies:
stream_chat_flutter_core: ^2.0.0
```
Upon doing this, all breaking changes from the package will take immediate effect. Here are steps to
remedy the issue:
:::note
The major changes in `stream_chat_flutter_core` consist of changing over from a map full of options
to a more type safe and sound approach by changing over to explicit parameters.
:::
1) Change over Core widget implementations by using the explicit parameters instead of the options map.
Use these explicit parameters in the widget constructor instead of the option keys:
* `options.state` -> `bool state`
* `options.watch` -> `bool watch`
* `options.presence` -> `bool presence`
2) Change over query calls in the BLoCs in the same way (change from options map to explicit parameters
in the constructor)
### Changelog of `stream_chat`
#### 🛑️ Breaking Changes from 1.5.3
* Migrate this package to null safety
* `ConnectUserWithProvider` now requires `tokenProvider` as a required param. (Removed from the constructor)
* `client.disconnect()` is now divided into two different functions
* `client.closeConnection()` -> for closing user websocket connection.
* `client.disconnectUser()` -> for disconnecting user and resetting client state.
* `client.devToken()` now returns a Token model instead of String.
* `ApiError` is removed in favor of `StreamChatError`
* `StreamChatError` -> parent type for all the stream errors.
* `StreamWebSocketError` -> for user websocket related errors.
* `StreamChatNetworkError` -> for network related errors.
* `client.queryChannels()`, `channel.query()` options param is removed in favor of individual params
* `option.state` -> `bool state`
* `option.watch` -> `bool watch`
* `option.presence` -> `bool presence`
* `client.queryUsers()` options param is removed in favor of individual params
* `option.presence` -> `bool presence`
* Added typed filters
#### 🐞 Fixed
* #369: Client does not return without internet connection
* Several minor fixes
* Performance improvements
#### ✅ Added
* New Location enum is introduced for easily changing the client location/baseUrl.
* New `client.openConnection()` and `client.closeConnection()` is introduced to connect/disconnect user ws connection.
* New `client.partialUpdateMessage` and `channel.partialUpdateMessage` methods
* `connectWebSocket` parameter in connect user calls to use the client in "connection-less" mode.
#### 🔄 Changed
* `baseURL` is now deprecated in favor of using Location to change data location.
### Migrating to 2.0 for `stream_chat`
If you are migrating your full Flutter project to null-safety, first make sure you follow the
instructions from the [official Null Safety migration guide](https://dart.dev/null-safety/migration-guide).
:::
To migrate to v2.0 for `stream_chat`, first change the version of the package to the latest
null-safe version.
```yaml
dependencies:
stream_chat: ^2.0.0
```
Upon doing this, all breaking changes from the package will take immediate effect. Here are steps to
remedy the issues:
1) Change over the constructor of `connectUserWithProvider()` to the new format which has `tokenProvider` as a required param.
2) We added more nuance to `disconnectUser()` by adding two new methods - one to close the connection
and the other to disconnect the user. This allows more fine-grained control of disconnection.
* `client.closeConnection()` -> for closing user websocket connection.
* `client.disconnectUser()` -> for disconnecting user and resetting client state.
3) We refactored how we handle errors - new error types are now introduced that replace ApiError.
* `StreamChatError` -> parent type for all the stream errors.
* `StreamWebSocketError` -> for user websocket related errors.
* `StreamChatNetworkError` -> for network related errors.
4) We changed over from a map full of options to a more type-safe and sound approach by changing over to explicit parameters.
Use these explicit parameters in the query parameters instead of the option keys:
* `client.queryChannels()`, `channel.query()` options param is removed in favor of individual params
* `option.state` -> `bool state`
* `option.watch` -> `bool watch`
* `option.presence` -> `bool presence`
* `client.queryUsers()` options param is removed in favor of individual params
* `option.presence` -> `bool presence`
5) We added type-safe filters to make filtering in the app easier. Change over the filters to the
new implementation.
As an example, in the old app this filter:
```dart
filter: {
'members': {
'\$in': [StreamChat.of(context).user.id],
}
},
```
Would turn into:
```dart
filter: Filter.in_('members', [StreamChat.of(context).user.id])
```
@@ -0,0 +1,4 @@
{
"label": "Stream Chat Flutter",
"position": 3
}
@@ -0,0 +1,84 @@
---
id: channel_header
sidebar_position: 10
title: ChannelHeader
---
A Widget To Display Common Channel Details
Find the pub.dev documentation [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/ChannelHeader-class.html)
![](../assets/channel_header.png)
### Background
When a user opens a channel, it is helpful to provide context of which channel they are in. This may
be in the form of a channel name or the users in the channel. Along with that, there also needs to be
a way for the user to look at more details of the channel (media, pinned messages, actions, etc.) and
preferably also a way to navigate back to where they came from.
To encapsulate all of this functionality into one widget, the Flutter SDK contains a `ChannelHeader`
widget which provides these out of the box.
### Basic Example
Let's just add a `ChannelHeader` to a page with a `MessageListView` and a `MessageInput` to display
and send messages.
```dart
class ChannelPage extends StatelessWidget {
const ChannelPage({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
body: Column(
children: <Widget>[
Expanded(
child: MessageListView(
threadBuilder: (_, parentMessage) {
return ThreadPage(
parent: parentMessage,
);
},
),
),
MessageInput(),
],
),
);
}
}
```
### Customizing Parts Of The Header
The header works like a `ListTile` widget.
Use the `title`, `subtitle`, `leading`, or `actions` parameters to substitute the widgets for your own.
```dart
//...
ChannelHeader(
title: Text('My Custom Name'),
),
```
![](../assets/channel_header_custom_title.png)
### Showing Connection State
The `ChannelHeader` can also display connection state below the tile which shows the user if they
are connected or offline, etc. on connection events.
To enable this, use the `showConnectionStateTile` property.
```dart
//...
ChannelHeader(
showConnectionStateTile: true,
),
```
@@ -0,0 +1,88 @@
---
id: channel_list_header
sidebar_position: 9
title: ChannelListHeader
---
A Header Widget For A List Of Channels
Find the pub.dev documentation [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/ChannelListHeader-class.html)
![](../assets/channel_list_header.png)
### Background
A common pattern for most messaging apps is to show a list of Channels (chats) on the first screen
and navigate to an individual one on being clicked. On this first page where the list of channels are
displayed, it is usual to have functionality such as adding a new chat, display the user logged in, etc.
To encapsulate all of this functionality into one widget, the Flutter SDK contains a `ChannelListHeader`
widget which provides these out of the box.
### Basic Example
This is a basic example of a page which has a `ChannelListView` and a `ChannelListHeader` to recreate a
common Channels Page.
```dart
class DemoPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelListHeader(),
body: ChannelsBloc(
child: ChannelListView(
filter: Filter.in_('members', [StreamChat.of(context).user.id]),
sort: [SortOption('last_message_at')],
pagination: PaginationParams(
limit: 20,
),
channelWidget: ChannelPage(),
),
),
);
}
}
```
### Customizing Parts Of The Header
The header works like a `ListTile` widget.
Use the `titleBuilder`, `subtitle`, `leading`, or `actions` parameters to substitute the widgets for your own.
```dart
//...
ChannelListHeader(
subtitle: Text('My Custom Subtitle'),
),
```
![](../assets/channel_list_header_custom_subtitle.png)
The `titleBuilder` param helps you build different titles depending on the connection state:
```dart
//...
ChannelListHeader(
titleBuilder: (context, status, client) {
switch(status) {
/// Return your title widget
}
},
),
```
### Showing Connection State
The `ChannelListHeader` can also display connection state below the tile which shows the user if they
are connected or offline, etc. on connection events.
To enable this, use the `showConnectionStateTile` property.
```dart
//...
ChannelListHeader(
showConnectionStateTile: true,
),
```
@@ -0,0 +1,111 @@
---
id: channel_list_view
sidebar_position: 4
title: ChannelListView
---
A Widget For Displaying A List Of Channels
Find the pub.dev documentation [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/ChannelListView-class.html)
![](../assets/channel_list_view.png)
### Background
Channels are fundamental elements of Stream Chat and constitute shared spaces which allow users to
message each other.
1:1 conversations and groups are both examples of channels, albeit with some (distinct/non-distinct)
differences. Displaying the list of channels that a user is a part of is a pattern present in most messaging apps.
The `ChannelListView` widget allows displaying a list of channels to a user. By default, this is NOT
ONLY the channels that the user is a part of. This section goes into setting up and using a `ChannelListView`
widget.
### Basic Example
Here is a basic example of the `ChannelListView` widget. It consists of the main widget itself, a `Filter`
to filter only the channels that the user is a part of, sorting by last message time, pagination params,
and the widget to use when a particular channel is clicked.
```dart
class ChannelListPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ChannelsBloc(
child: ChannelListView(
filter: Filter.in_('members', [StreamChat.of(context).user.id]),
sort: [SortOption('last_message_at')],
pagination: PaginationParams(
limit: 20,
),
channelWidget: ChannelPage(),
),
),
);
}
}
```
This example by default displays the channels that a user is a part of. Now let's look at customizing
the widget.
### Customizing the Channel Preview
A common aspect of the widget needed to be tweaked according to each app is the Channel Preview (the
Channel tile in the list). To do this, we use the `channelPreviewBuilder` param like this:
```dart
ChannelListView(
...
channelPreviewBuilder: (context, channel) {
return ListTile(
tileColor: Colors.amberAccent,
title: Center(
child: ChannelName(),
),
);
},
),
```
Which gives you a new Channel preview in the list:
![](../assets/channel_preview.png)
### Adding Swipe Actions
To add actions (such as delete, more info, etc) when Channel preview is swiped left, set the `swipeToAction`
parameter to `true`.
```dart
ChannelListView(
...
swipeToAction: true,
),
```
This adds two basic actions - info and delete:
![](../assets/swipe_channel.png)
To add custom actions of your own, use the `swipeActions` param:
```dart
ChannelListView(
...
swipeToAction: true,
swipeActions: [
SwipeAction(
color: Colors.blue,
iconWidget: Icon(Icons.add),
onTap: (channel) {
// Things to do on icon tap
},
),
// Other actions here
]
),
```
@@ -0,0 +1,18 @@
---
id: introduction
sidebar_position: 1
title: Introduction
---
Understanding The UI Package Of The Flutter SDK
### What function does `stream_chat_flutter` serve?
The UI SDK (`stream_chat_flutter`) contains official Flutter components for Stream Chat, a service for building chat applications.
While the Stream Chat service provides the backend for messaging and the LLC provides an easy way to
use it in your Flutter apps, we wanted to make sure that adding Chat functionality to your app was as quick as possible.
The UI package is built on top of the low-level client and the core package and allows you to build a
full fledged app with either the inbuilt components, modify existing components, or easily add widgets
of your own to match your app's style better.
@@ -0,0 +1,170 @@
---
id: message_input
sidebar_position: 6
title: MessageInput
---
A Widget Dealing With Everything Related To Sending A Message
Find the pub.dev documentation [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/MessageInput-class.html)
![](../assets/message_input.png)
### Background
In Stream Chat, we can send messages in a channel. However, sending a message isn't as simple as adding
a `TextField` and logic for sending a message. It involves additional processes like addition of media,
quoting a message, adding a custom command like a GIF board, and much more. Moreover, most apps also
need to customize the input to match their theme, overall color and structure pattern, etc.
To do this, we created a `MessageInput` widget which abstracts all expected functionality a modern input
needs - and allows you to use it out of the box.
### Basic Example
A `StreamChannel` is required above the widget tree in which the `MessageInput` is rendered since the channel is
where the messages sent actually go. Let's look at a common example of how we could use the `MessageInput`:
```dart
class ChannelPage extends StatelessWidget {
const ChannelPage({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
body: Column(
children: <Widget>[
Expanded(
child: MessageListView(
threadBuilder: (_, parentMessage) {
return ThreadPage(
parent: parentMessage,
);
},
),
),
MessageInput(),
],
),
);
}
}
```
It is common to put this widget in the same page of a `MessageListView` as the bottom widget.
### Quoting A Message
The quoting functionality allows us to 'reply' to a specific message without creating a thread out of it.
It adds the other message as context when sending a message and also displays it above the sent message.
To quote a message, we provide a `quotedMessage` to the `MessageInput`.
```dart
Message? message;
// ...
MessageInput(
quotedMessage: message,
),
```
This will add the message given above the message about to be sent.
While you can implement your own functionality to select which message to reply to, the `MessageListView`
widget helps in this case since it has an inbuilt `onMessageSwiped` callback which we can use.
```dart
class ChannelPage extends StatefulWidget {
@override
_ChannelPageState createState() => _ChannelPageState();
}
class _ChannelPageState extends State<ChannelPage> {
Message? quotedMessage;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(
child: MessageListView(
// ...
onMessageSwiped: (message) {
setState(() {
quotedMessage = message;
});
},
),
),
MessageInput(
quotedMessage: _quotedMessage,
onQuotedMessageCleared: () {
setState(() => _quotedMessage = null);
},
),
],
),
);
}
}
```
![](../assets/message_input_quoted_message.png)
### Adding Custom Actions
By default, the `MessageInput` has two actions: one for attachments and one for commands like Giphy.
To add your own action, we use the `actions` parameter like this:
```dart
MessageInput(
actions: [
InkWell(
child: Icon(
Icons.location_on,
size: 20.0,
color: StreamChatTheme.of(context).colorTheme.grey,
),
onTap: () {
// Do something here
},
),
],
),
```
This will add on your action to the existing ones.
### Disable Attachments
To disable attachments being added to the message, set the `disableAttachments` parameter to true.
```dart
MessageInput(
disableAttachments: true,
),
```
### Changing Position Of MessageInput Components
You can also change the position of the TextField, actions and 'send' button relative to each other.
To do this, use the `actionsLocation` or `sendButtonLocation` parameters which help you decide the location
of the buttons in the input.
For example, if we want the actions on the right and the send button inside the TextField, we can do:
```dart
MessageInput(
sendButtonLocation: SendButtonLocation.inside,
actionsLocation: ActionsLocation.right,
),
```
![](../assets/message_input_change_position.png)
@@ -0,0 +1,115 @@
---
id: message_list_view
sidebar_position: 5
title: MessageListView
---
A Widget For Displaying A List Of Messages
Find the pub.dev documentation [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/MessageListView-class.html)
![](../assets/message_list_view.png)
### Background
Every channel can contain a list of messages sent by users inside it. The `MessageListView` widget
displays the list of messages inside a particular channel along with possible attachments and
other message attributes (if the message is pinned for example). This sets it apart from the `MessageSearchListView`
which may not contain messages only from a single channel and is used to search for messages across
many.
### Basic Example
The `MessageListView` shows the list of messages of the current channel. It has inbuilt support for
common messaging functionality: displaying and editing messages, adding / modifying reactions, support
for quoting messages, pinning messages, and more.
An example of how you can use the MessageListView is:
```dart
class ChannelPage extends StatelessWidget {
const ChannelPage({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
body: Column(
children: <Widget>[
Expanded(
child: MessageListView(
threadBuilder: (_, parentMessage) {
return ThreadPage(
parent: parentMessage,
);
},
),
),
MessageInput(),
],
),
);
}
}
```
### Enable Threads
Threads are made of a parent message and replies linked to it. To enable threading, the SDK requires you
to supply a `threadBuilder` which will supply the page when the thread is clicked.
```dart
MessageListView(
threadBuilder: (_, parentMessage) {
return ThreadPage(
parent: parentMessage,
);
},
),
```
![](../assets/message_list_view_threads.png)
The `MessageListView` itself can render the thread by supplying the `parentMessage` parameter.
```dart
MessageListView(
parentMessage: parent,
),
```
### Building Custom Messages
You can also supply your own implementation for displaying messages using the `messageBuilder` parameter.
:::note
To customize the existing implementation, look at the `MessageWidget` documentation instead.
:::
```dart
MessageListView(
messageBuilder: (context, details, messageList, defaultImpl) {
// Your implementation of the message here
// E.g: return Text(details.message.text ?? '');
},
),
```
### Enabling Message Pinning
Message pins save and highlight the message in the `MessageListView`. To enable users to pin the message,
make sure the pin permissions are granted for different types of users on the dashboard. After confirming
the appropriate users have permissions, add the user types in the `pinPermissions` parameter.
```dart
MessageListView(
//...
pinPermissions: ['admin', 'userType1', 'userType2'],
),
```
This will allow these user types to pin messages through the message actions modal.
![](../assets/message_list_view_pin.png)
@@ -0,0 +1,62 @@
---
id: message_search_list_view
sidebar_position: 8
title: MessageSearchListView
---
A Widget To Search For Messages Across Channels
Find the pub.dev documentation [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/MessageSearchListView-class.html)
![](../assets/message_search_list_view.png)
### Background
Users in Stream Chat can have several channels and it can get hard to remember which channel has the
message they are searching for. As such, there needs to be a way to search for a message across multiple
channels. This is where `MessageSearchListView` comes in.
### Basic Example
While the MessageListView is tied to a certain `StreamChannel`, a `MessageSearchListView` is not.
```dart
class MessageSearchPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: MessageSearchBloc(
child: MessageSearchListView(
filters: Filter.in_('members', [StreamChat.of(context).user!.id],),
messageQuery: 'your query here',
paginationParams: PaginationParams(limit: 20),
),
),
);
}
}
```
### Customize The Result Tiles
You can use your own widget for the result items using the `itemBuilder` parameter.
```dart
MessageSearchListView(
// ...
itemBuilder: (context, response) {
return Text(response.message.text);
},
),
```
### Show Result Count
You show the number of results via the `showResultCount` parameter.
```dart
MessageSearchListView(
// ...
showResultCount: true,
),
```
@@ -0,0 +1,98 @@
---
id: message_widget
sidebar_position: 11
title: MessageWidget
---
A Widget For Displaying Messages And Attachments
Find the pub.dev documentation [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/MessageWidget-class.html)
### Background
There are several things that need to be displayed with text in a message in a modern messaging app:
attachments, highlights if the message is pinned, user avatars of the sender, etc.
To encapsulate all of this functionality into one widget, the Flutter SDK contains a `MessageWidget`
widget which provides these out of the box.
### Basic Example (Modifying `MessageWidget` in `MessageListView`)
Primarily, the `MessageWidget` is used in the `MessageListView`. To customize only a few properties
of the `MessageWidget` without supplying all other properties, the `messageBuilder` builder supplies
a default implementation of the widget for us to modify.
```dart
class ChannelPage extends StatelessWidget {
const ChannelPage({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: MessageListView(
messageBuilder: (context, details, messageList, defaultMessageWidget) {
return defaultMessageWidget.copyWith(
showThreadReplyIndicator: false,
);
},
),
);
}
}
```
### Building A Custom Attachment
When a custom attachment type (location, audio, etc.) is sent, the MessageWidget also needs to know
how to build it. For this purpose, we can use the `customAttachmentBuilders` parameter.
As an example, if a message has a attachment type 'location', we do:
```dart
MessageWidget(
//...
customAttachmentBuilders: {
'location': (context, message, attachments) {
var attachmentWidget = Image.network(
_buildMapAttachment(
attachments[0].extraData['latitude'],
attachments[0].extraData['longitude'],
),
);
return wrapAttachmentWidget(context, attachmentWidget, null, true, BorderRadius.circular(8.0));
}
},
)
```
You can also override the builder for existing attachment types like `image` and `video`.
### Show User Avatar For Messages
You can decide to show, hide, or remove user avatars of the sender of the message. To do this, set
the `showUserAvatar` property like this:
```dart
MessageWidget(
//...
showUserAvatar = DisplayWidget.show,
)
```
### Reverse the message
In most cases, `MessageWidget` needs to be a different orientation depending upon if the sender is the
user or someone else.
For this, we use the `reverse` parameter to change the orientation of the message:
```dart
MessageWidget(
//...
reverse = true,
)
```
@@ -0,0 +1,48 @@
---
id: setup
sidebar_position: 2
title: Setup
---
Understanding Setup For `stream_chat_flutter`
### Add pub.dev dependency
First, you need to add the `stream_chat_flutter` dependency to your `pubspec.yaml`.
You can either run this command:
```shell
flutter pub add stream_chat_flutter
```
OR
Add this line in the dependencies section of your pubspec.yaml after substituting latest version:
```yaml
dependencies:
stream_chat_flutter: ^latest_version
```
You can find the package details on [pub.dev](https://pub.dev/packages/stream_chat_flutter).
### Details On Platform Support
`stream_chat_flutter` was originally created for Android and iOS mobile platforms. As Flutter matured,
support for additional platforms was added and the package now has experimental support for web and desktop as
[detailed here](https://getstream.io/blog/announcing-experimental-multi-platform-support-for-the-stream-flutter-sdk/).
However, platforms other than mobile may have additional constraints due to not supporting all plugins,
which will be addressed by the respective plugin creators over time.
### Setup: iOS
The library uses [flutter file picker plugin](https://github.com/miguelpruivo/flutter_file_picker) to pick files from the os.
Follow [this wiki](https://github.com/miguelpruivo/flutter_file_picker/wiki/Setup#ios) to fulfill iOS requirements.
We also use [video_player](https://pub.dev/packages/video_player) to reproduce videos.
Follow [this guide](https://pub.dev/packages/video_player#installation) to fulfill the requirements.
To pick images from the camera, we use the [image_picker](https://pub.dev/packages/image_picker) plugin.
Follow [these instructions](https://pub.dev/packages/image_picker#ios) to check the requirements.
@@ -0,0 +1,71 @@
---
id: stream_chat_and_theming
sidebar_position: 3
title: StreamChat And Theming
---
Understanding How To Customize Widgets Using `StreamChatTheme`
Find the pub.dev documentation [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/StreamChatTheme-class.html) and [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/StreamChatThemeData-class.html)
### Background
Stream's UI SDK makes it easy for developers to add custom styles and attributes to our widgets. Like most Flutter frameworks, Stream exposes a dedicated widget for theming.
Using `StreamChatTheme`, users can customize most aspects of our UI widgets by setting attributes using `StreamChatThemeData`.
Similar to the `Theme` and `ThemeData` in Flutter, Stream Chat uses a top level [inherited widget](https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html) to provide theming information throughout your application. This can be optionally set at the top of your application tree or at a localized point in your widget sub-tree.
If you'd like to customize the look and feel of Stream chat across your entire application, we recommend setting your theme at the top level. Conversely, users can customize specific screens or widgets by wrapping components in a `StreamChatTheme`.
### A closer look at StreamChatThemeData
Looking at the constructor for `StreamChatThemeData`, we can see the full list of properties and widgets available for customization.
Some high-level properties such as `textTheme` or `colorTheme` can be set application-wide directly from this class. In contrast, larger components such as `ChannelHeader`, `MessageInputs`, etc. have been broken up into smaller theme objects.
```dart
factory StreamChatThemeData({
Brightness? brightness,
TextTheme? textTheme,
ColorTheme? colorTheme,
ChannelListHeaderTheme? channelListHeaderTheme,
ChannelPreviewTheme? channelPreviewTheme,
ChannelTheme? channelTheme,
MessageTheme? otherMessageTheme,
MessageTheme? ownMessageTheme,
MessageInputTheme? messageInputTheme,
Widget Function(BuildContext, Channel)? defaultChannelImage,
Widget Function(BuildContext, User)? defaultUserImage,
IconThemeData? primaryIconTheme,
List<ReactionIcon>? reactionIcons,
});
```
### Stream Chat Theme in use
Let's take a look at customizing widgets using `StreamChatTheme`. In the example below, we can change the default color theme to yellow and override the channel header's typography and colors.
```dart
builder: (context, child) => StreamChat(
client: client,
child: child,
streamChatThemeData: StreamChatThemeData(
colorTheme: ColorTheme.light(
primaryAccent: const Color(0xffffe072),
),
channelTheme: ChannelTheme(
channelHeaderTheme: ChannelHeaderTheme(
color: const Color(0xffd34646),
title: TextStyle(
color: Colors.white,
),
),
),
),
),
```
We are creating this class at the very top of our widget tree using the `streamChatThemeData` parameter found in the `StreamChat` widget.
![](../assets/using_theme.jpg)
@@ -0,0 +1,88 @@
---
id: user_list_view
sidebar_position: 7
title: UserListView
---
A Widget For Displaying And Selecting Users
Find the pub.dev documentation [here](https://pub.dev/documentation/stream_chat_flutter/latest/stream_chat_flutter/UserListView-class.html)
![](../assets/user_list_view.png)
### Background
A list of users is required for many different purposes: showing a list of users in a Channel,
selecting users to add in a channel, etc. The `UserListView` displays and allows selection of a list
of users along with multiple display configurations like a list and grid.
### Basic Example
Let's take a look at an example where we use the widget to autocomplete user names:
```dart
class UsersListPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: UsersBloc(
child: UsersListView(
filter: Filter.notEqual('id', StreamChat.of(context).user!.id),
sort: [
SortOption(
'name',
direction: 1,
),
],
pagination: PaginationParams(
limit: 25,
),
),
),
);
}
}
```
### Customize The User Items
You can use your own widget for the user items using the `userItemBuilder` parameter.
```dart
UsersListView(
// ...
userItemBuilder: (context, user, isSelected) {
return Text(user.name);
},
),
```
### Group Alphabetically
You can group alphabetically using the `groupAlphabetically` parameter:
```dart
UsersListView(
//...
groupAlphabetically: true,
),
```
### Selecting Users
The `UserListView` widget allows selecting users in a list by supplying a selected users list and callbacks
for when user items are tapped.
```dart
Set<User>? selectedUsers = {};
UsersListView(
//...
selectedUsers: selectedUsers,
onUserTap: (user, _) {
setState(() {
selectedUsers.add(user);
});
},
),
```
@@ -0,0 +1,4 @@
{
"label": "Stream Chat Flutter Core",
"position": 4
}
@@ -0,0 +1,68 @@
---
id: channel_list_core
sidebar_position: 4
title: ChannelListCore
---
A Widget For Building A List Of Channels
### Background
The UI SDK of Stream Chat supplies a `ChannelListView` class that builds a list of channels fetching
according to the filters and sort order given. However, in some cases, implementing novel UI is necessary
that cannot be done using the customization approaches given in the widget.
To do this, we extracted the logic required for fetching channels into a 'Core' widget - a widget that
fetches channels in the expected way via the usual params but does not supply any UI and instead
exposes builders to build the UI in situations such as loading, empty data, errors, and on data received.
### Basic Example
`ChannelListCore` is a simplified class that allows fetching a list of
channels while exposing UI builders.
This allows you to construct your own UI while not having to
worry about the specific logic of fetching channels in your app.
A `ChannelListController` is used to reload and paginate data.
```dart
class ChannelListPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ChannelListCore(
filter: Filter.in_(
'members',
[StreamChat.of(context).user!.id],
),
sort: [SortOption('last_message_at')],
pagination: PaginationParams(
limit: 20,
),
errorBuilder: (context, err) {
return Center(
child: Text('An error has occured'),
);
},
emptyBuilder: (context) {
return Center(
child: Text('Nothing here...'),
);
},
loadingBuilder: (context) {
return Center(
child: CircularProgressIndicator(),
);
},
listBuilder: (context, list) {
return ChannelPage(list);
}
),
);
}
}
```
Make sure to have a `StreamChatCore` ancestor in order to provide the
information about the channels.
@@ -0,0 +1,90 @@
---
id: channels_bloc
sidebar_position: 7
title: ChannelsBloc
---
A Widget Dedicated To The Management Of A Channel List With Pagination.
### Background
Most widgets in the Core SDK are focused on fetching a particular type of object from Stream Chat - channels,
messages, users, etc. The BLoC widgets bundle up the base functions used to fetch data as well as the current
data fetched by the respective functions. Furthermore, the Core widgets use this BLoC to fetch new or
existing data and build UI based on it.
All Core and UI widgets which focus on fetching a list of objects need to have their respective functions
above them in the widget tree. The ChannelListCore and ChannelListView require the ChannelsBloc
above them in the widget hierarchy without which they will fail.
### Understanding The Widget
`ChannelsBloc` is used together with `ChannelListCore` to manage a list of
Channels with pagination, re-ordering, querying and other operations
associated with Channels.
`ChannelsBloc` can be accessed at anytime by using the static `.of` method
using Flutter's `BuildContext`.
```dart
var _channelsBloc = ChannelsBloc.of(context);
```
The `ChannelsBloc` widget encapsulates common functionality related to channel lists such as fetching
the existing channels and querying new channels and also supplies them down the widget tree.
The widget is required for the respective core widget (`ChannelListCore`) to fetch channels and hence
must be above the core widget in the tree.
Here is a basic implementation of `ChannelsBloc`:
```dart
ChannelsBloc(
child: // Further Widget Tree
),
```
The `ChannelsBloc` widget allows three customisations:
#### Lock Channels Order
ChannelsBloc may change the order of channels when new messages arrive. To lock this order, we can
set the `lockChannelsOrder` property to true.
```dart
ChannelsBloc(
lockChannelsOrder: true,
child: // Further Widget Tree
),
```
#### Set custom channel order
We can decide the order of the channels in the list by supplying a comparator to the `channelsComparator`
parameter:
```dart
ChannelsBloc(
channelsComparator: (a, b) {
return a.createdAt!.millisecondsSinceEpoch >
b.createdAt!.millisecondsSinceEpoch
? 1
: -1;
},
child: // Further Widget Tree
),
```
#### Decide if channel should be added on new message event
When a new message arrives, a `message.new` event is received. We can decide if we want to add the channel
to the list using the `shouldAddChannel` parameter which is a callback supplying the event data:
```dart
ChannelsBloc(
shouldAddChannel: (event) {
return event.message!.extraData['priority'] == '1';
},
child: // Further Widget Tree
),
```
@@ -0,0 +1,80 @@
---
id: introduction
sidebar_position: 1
title: Introduction
---
Understanding The Core Package Of The Flutter SDK
This package provides business logic to fetch common things required for integrating Stream Chat into your application.
The core package allows more customisation and hence provides business logic but no UI components.
Please use the `stream_chat_flutter` package for the full fledged suite of UI components or `stream_chat` for the low-level client.
### Background
In the early days of the Flutter SDK, the SDK was only split into the LLC (`stream_chat`) and
the UI package (`stream_chat_flutter`). With this you could use a fully built interface with the UI package
or a fully custom interface with the LLC. However, we soon recognised the need for a third intermediary
package which made tasks like building and modifying a list of channels or messages easy but without
the complexity of using low level components. The Core package (`stream_chat_flutter_core`) is a manifestation
of the same idea and allows you to build an interface with Stream Chat without having to deal with
low level code and architecture as well as implementing your own theme and UI effortlessly.
Also, it has very few dependencies.
We will now explore the components of this intermediary package and understand how it helps you build
the experience you want your users to have.
The package primarily contains three types of classes:
* Business Logic Components
* Core Components
* Core Controllers
### Business Logic Components
These components allow you to have the maximum and lower-level control of the queries being executed.
In BLoCs, the basic functionalities - such as queries for messages, channels or queries - are bundled up
and passed along down the tree. Using a BLoC allows you to either create your own way to fetch and
build UIs or use an inbuilt Core widget to do the work such as queries, pagination, etc for you.
The BLoCs we provide are:
* ChannelsBloc
* MessageSearchBloc
* UsersBloc
### Core Components
Core components usually are an easy way to fetch data associated with Stream Chat.
Core components use functions exposed by the respective BLoCs (for example the ChannelListCore uses the ChannelsBloc)
and use the respective controllers for various operations. Unlike heavier components from the UI
package, core components are decoupled from UI and they expose builders instead to help you build
a fully custom interface.
Data fetching can be controlled with the controllers of the respective core components.
* ChannelListCore (Fetch a list of channels)
* MessageListCore (Fetch a list of messages from a channel)
* MessageSearchListCore (Fetch a list of search messages)
* UserListCore (Fetch a list of users)
* StreamChatCore (This is different from the other core components - it is a version of StreamChat decoupled from theme and initialisations.)
### Core Controllers
Core Controllers are supplied to respective CoreList widgets which allows reloading and pagination of data whenever needed.
Unlike the UI package, the Core package allows a fully custom user interface built with the data. This
in turn provides a few challenges: we do not know implicitly when to paginate your list or reload your data.
While this is handled out of the box in the UI package since the List implementation is inbuilt, a controller
needs to be used in the core package notifying the core components to reload or paginate the data existing
currently. For this, each core component has a respective controller which you can use to call the
specific function (reload / paginate) whenever such an event is triggered through / needed in your UI.
* ChannelListController
* MessageListController
* MessageSearchListController
* ChannelListController
This section goes into the individual core package widgets and their functional use.
@@ -0,0 +1,70 @@
---
id: message_list_core
sidebar_position: 5
title: MessageListCore
---
A Widget For Building A List Of Messages
### Background
The UI SDK of Stream Chat supplies a `MessageListView` class that builds a list of channels fetching
according to the filters and sort order given. However, in some cases, implementing novel UI is necessary
that cannot be done using the customization approaches given in the widget.
To do this, we extracted the logic required for fetching channels into a 'Core' widget - a widget that
fetches channels in the expected way via the usual params but does not supply any UI and instead
exposes builders to build the UI in situations such as loading, empty data, errors, and on data received.
### Basic Example
`MessageListCore` is a simplified class that allows fetching a list of
messages while exposing UI builders.
This allows you to construct your own UI while not having to
worry about the specific logic of fetching messages in a channel.
A `MessageListController` is used to paginate data.
```dart
class ChannelPage extends StatelessWidget {
const ChannelPage({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(
child: MessageListCore(
emptyBuilder: (context) {
return Center(
child: Text('Nothing here...'),
);
},
loadingBuilder: (context) {
return Center(
child: CircularProgressIndicator(),
);
},
messageListBuilder: (context, list) {
return MessagesPage(list);
},
errorWidgetBuilder: (context, err) {
return Center(
child: Text('Error'),
);
},
),
),
],
),
);
}
}
```
Make sure to have a `StreamChannel` ancestor in order to provide the
information about the channels.
@@ -0,0 +1,40 @@
---
id: message_search_list_block
sidebar_position: 8
title: MessageSearchListBloc
---
A Widget Used To Manage A List Of Messages With Pagination.
### Background
Most widgets in the Core SDK are focused on fetching a particular type of object from Stream Chat - channels,
messages, users etc. The BLoC widgets bundle up the base functions used to fetch data as well as the current
data fetched by the respective functions. Furthermore, the Core widgets use this BLoC to fetch new or
existing data and build UI based on it.
All Core and UI widgets which focus on fetching a list of objects need to have their respective functions
above them in the widget tree. The MessageSearchListCore and MessageSearchListView require the
MessageSearchListCore above them in the widget hierarchy without which they will fail.
### Understanding The Widget
This class can be used to load messages, perform queries, etc.
`MessageSearchBloc` can be accessed at anytime by using the static `.of` method
using Flutter's BuildContext.
```dart
var _searchBloc = MessageSearchBloc.of(context);
```
The `MessageSearchBloc` widget encapsulates common functionality related to searching for messages
across channels and also supplies them down the widget tree.
Here is a basic implementation of `ChannelsBloc`:
```dart
MessageSearchBloc(
child: // Further Widget Tree
),
```
@@ -0,0 +1,41 @@
---
id: message_search_list_core
sidebar_position: 6
title: MessageSearchListCore
---
A Widget For Displaying Message Searches
### Background
The UI SDK of Stream Chat supplies a `MessageSearchListView` class that builds a list of channels fetching
according to the filters and sort order given. However, in some cases, implementing novel UI is necessary
that cannot be done using the customization approaches given in the widget.
To do this, we extracted the logic required for fetching channels into a 'Core' widget - a widget that
fetches channels in the expected way via the usual params but does not supply any UI and instead
exposes builders to build the UI in situations such as loading, empty data, errors, and on data received.
### Basic Example
`MessageSearchListCore` is a simplified class that allows searching for
messages across channels while exposing UI builders.
A `MessageSearchListController` is used to load and paginate data.
```dart
class MessageSearchPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: MessageSearchListCore(
messageQuery: _messageFilter,
filters: _channelsFilter,
paginationParams: PaginationParams(limit: 20),
),
);
}
}
```
Make sure to have a `MessageSearchBloc` ancestor in order to provide the
information about the messages.
@@ -0,0 +1,28 @@
---
id: setup
sidebar_position: 2
title: Setup
---
Understanding Setup For `stream_chat_flutter_core`
### Add pub.dev dependency
First, you need to add the `stream_chat_flutter_core` dependency to your pubspec.yaml
You can either run this command:
```shell
flutter pub add stream_chat_flutter_core
```
OR
Add this line in the dependencies section of your pubspec.yaml after substituting latest version:
```yaml
dependencies:
stream_chat_flutter_core: ^latest_version
```
You can find the package details on [pub.dev](https://pub.dev/packages/stream_chat_flutter_core).
@@ -0,0 +1,26 @@
---
id: stream_chat_core
sidebar_position: 3
title: StreamChatCore
---
`StreamChatCore` is a version of `StreamChat` found in `stream_chat_flutter` that is decoupled from
theme and initialisations.
`StreamChatCore` is used to provide information about the chat client to the widget tree.
This Widget is used to react to life cycle changes and system updates.
When the app goes into the background, the websocket connection is automatically closed and when it goes back to foreground the connection is opened again.
Like the `StreamChat` widget in the higher level UI package, the `StreamChatCore` widget should
be on the top level before using any Stream functionality:
```dart
return MaterialApp(
title: 'Stream Chat Core Example',
home: HomeScreen(),
builder: (context, child) => StreamChatCore(
client: client,
child: child!,
),
);
```
@@ -0,0 +1,64 @@
---
id: user_list_core
sidebar_position: 10
title: UserListCore
---
A Widget For Building A List Of Users
### Background
The UI SDK of Stream Chat supplies a `UserListView` class that builds a list of channels fetching
according to the filters and sort order given. However, in some cases, implementing novel UI is necessary
that cannot be done using the customization approaches given in the widget.
To do this, we extracted the logic required for fetching channels into a 'Core' widget - a widget that
fetches channels in the expected way via the usual params but does not supply any UI and instead
exposes builders to build the UI in situations such as loading, empty data, errors, and on data received.
### Basic Example
`UserListCore` is a simplified class that allows fetching users while
exposing UI builders.
A `UserListController` is used to load and paginate data.
```dart
class UsersListPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: UsersListCore(
sort: [SortOption('last_active')],
pagination: PaginationParams(
limit: 20,
),
errorBuilder: (err) {
return Center(
child: Text('An error has occured'),
);
},
emptyBuilder: (context) {
return Center(
child: Text('Nothing here...'),
);
},
emptyBuilder: (context) {
return Center(
child: CircularProgressIndicator(),
);
},
listBuilder: (context, list) {
return UsersPage(list);
}
),
);
}
}
```
`UsersBloc` must be the ancestor of this widget. This is necessary since
`UserListCore` depends on functionality contained within `UsersBloc`.
The parameters `listBuilder`, `loadingBuilder`, `emptyBuilder` and
`errorBuilder` must all be supplied and not null.
@@ -0,0 +1,37 @@
---
id: users_bloc
sidebar_position: 9
title: UsersBloc
---
A Widget Dedicated To The Management Of A Users List With Pagination.
### Background
Most widgets in the Core SDK are focused on fetching a particular type of object from Stream Chat - channels,
messages, users, etc. The BLoC widgets bundle up the base functions used to fetch data as well as the current
data fetched by the respective functions. Furthermore, the Core widgets use this BLoC to fetch new or
existing data and build UI based on it.
All Core and UI widgets which focus on fetching a list of objects need to have their respective functions
above them in the widget tree. The UserListCore and UserListView require the UserListCore
above them in the widget hierarchy without which they will fail.
### Understanding The Widget
`UsersBloc` can be accessed at anytime by using the static `.of` method
using Flutter's `BuildContext`.
```dart
var _userBloc_ = UsersBloc.of(context);
```
The `UsersBloc` widget encapsulates common functionality related to user lists and also supplies them down the widget tree.
Here is a basic implementation of `UsersBloc`:
```dart
UsersBloc(
child: // Further Widget Tree
),
```
+46 -11
View File
@@ -1,3 +1,49 @@
## 2.0.0
🛑️ Breaking Changes from `1.5.3`
- migrate this package to null safety
- `ConnectUserWithProvider` now requires `tokenProvider` as a required param. (Removed from the constructor)
- `client.disconnect()` is now divided into two different functions
- `client.closeConnection()` -> for closing user websocket connection.
- `client.disconnectUser()` -> for disconnecting user and resetting client state.
- `client.devToken()` now returns a `Token` model instead of `String`.
- `ApiError` is removed in favor of `StreamChatError`
- `StreamChatError` -> parent type for all the stream errors.
- `StreamWebSocketError` -> for user websocket related errors.
- `StreamChatNetworkError` -> for network related errors.
- `client.queryChannels()`, `channel.query()` options param is removed in favor of individual params
- `option.state` -> bool state
- `option.watch` -> bool watch
- `option.presence` -> bool presence
- `client.queryUsers()` options param is removed in favor of individual params
- `option.presence` -> bool presence
- Migrate this package to null safety
- Added typed filters
🐞 Fixed
- [#369](https://github.com/GetStream/stream-chat-flutter/issues/369): Client does not return without internet connection
- several minor fixes
- performance improvements
✅ Added
- New `Location` enum is introduced for easily changing the client location/baseUrl.
- New `client.openConnection()` and `client.closeConnection()` is introduced to connect/disconnect user ws connection.
- New `client.partialUpdateMessage` and `channel.partialUpdateMessage` methods
- `connectWebSocket` parameter in connect user calls to use the client in "connection-less" mode.
🔄 Changed
- `baseURL` is now deprecated in favor of using `Location` to change data location.
## 2.0.0-nullsafety.8
🐞 Fixed
- Export `PushProvider` enum
## 2.0.0-nullsafety.7
🛑️ Breaking Changes from `2.0.0-nullsafety.6`
@@ -27,21 +73,10 @@
- `baseURL` is now deprecated in favor of using `Location` to change data location.
🐞 Fixed
- [#369](https://github.com/GetStream/stream-chat-flutter/issues/369): Client does not return without internet
connection
## 2.0.0-nullsafety.6
- Fix thread reply not working with attachments
- Minor fixes
## 2.0.0-nullsafety.6
- Fix thread reply not working with attachments
- Minor fixes
## 2.0.0-nullsafety.5
- Minor fixes
+76 -80
View File
@@ -13,7 +13,7 @@ Future<void> main() async {
await client.connectUser(
User(
id: 'cool-shadow-7',
extraData: {
extraData: const {
'image':
'https://getstream.io/random_png/?id=cool-shadow-7&amp;name=Cool+shadow',
},
@@ -57,12 +57,10 @@ class StreamExample extends StatelessWidget {
final Channel channel;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Stream Chat Dart Example',
home: HomeScreen(channel: channel),
);
}
Widget build(BuildContext context) => MaterialApp(
title: 'Stream Chat Dart Example',
home: HomeScreen(channel: channel),
);
}
/// Main screen of our application. The layout is comprised of an [AppBar]
@@ -167,83 +165,81 @@ class _MessageViewState extends State<MessageView> {
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: ListView.builder(
controller: _scrollController,
itemCount: _messages.length,
reverse: true,
itemBuilder: (BuildContext context, int index) {
final item = _messages[index];
if (item.user?.id == widget.channel.client.uid) {
return Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.all(8),
child: Text(item.text ?? ''),
),
);
} else {
return Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.all(8),
child: Text(item.text ?? ''),
),
);
}
},
Widget build(BuildContext context) => Column(
children: [
Expanded(
child: ListView.builder(
controller: _scrollController,
itemCount: _messages.length,
reverse: true,
itemBuilder: (BuildContext context, int index) {
final item = _messages[index];
if (item.user?.id == widget.channel.client.uid) {
return Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.all(8),
child: Text(item.text ?? ''),
),
);
} else {
return Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.all(8),
child: Text(item.text ?? ''),
),
);
}
},
),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Enter your message',
),
),
),
Material(
type: MaterialType.circle,
color: Colors.blue,
clipBehavior: Clip.hardEdge,
child: InkWell(
onTap: () async {
// We can send a new message by calling `sendMessage` on
// the current channel. After sending a message, the
// TextField is cleared and the list view is scrolled
// to show the new item.
if (_controller.value.text.isNotEmpty) {
await widget.channel.sendMessage(
Message(text: _controller.value.text),
);
_controller.clear();
_updateList();
}
},
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child: Icon(
Icons.send,
color: Colors.white,
),
Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Enter your message',
),
),
),
)
],
),
)
],
);
}
Material(
type: MaterialType.circle,
color: Colors.blue,
clipBehavior: Clip.hardEdge,
child: InkWell(
onTap: () async {
// We can send a new message by calling `sendMessage` on
// the current channel. After sending a message, the
// TextField is cleared and the list view is scrolled
// to show the new item.
if (_controller.value.text.isNotEmpty) {
await widget.channel.sendMessage(
Message(text: _controller.value.text),
);
_controller.clear();
_updateList();
}
},
child: const Padding(
padding: EdgeInsets.all(8),
child: Center(
child: Icon(
Icons.send,
color: Colors.white,
),
),
),
),
)
],
),
)
],
);
}
/// Helper extension for quickly retrieving
@@ -888,6 +888,7 @@ class Channel {
final oldMessage = state!.messages[oldIndex];
state!.updateChannelState(state!._channelState.copyWith(
messages: state?.messages?..remove(oldMessage),
channel: state?._channelState.channel,
));
} else {
// remove thread message if present
+56 -17
View File
@@ -220,27 +220,53 @@ class StreamChatClient {
/// Connects the current user, this triggers a connection to the API.
/// It returns a [Future] that resolves when the connection is setup.
Future<Event> connectUser(User user, String token) =>
_connectUser(user, token: Token.fromRawValue(token));
/// Pass [connectWebSocket]: false, if you want to connect to websocket
/// at a later stage or use the client in connection-less mode
Future<OwnUser> connectUser(
User user,
String token, {
bool connectWebSocket = true,
}) =>
_connectUser(
user,
token: Token.fromRawValue(token),
connectWebSocket: connectWebSocket,
);
/// Connects the current user using the [tokenProvider] to fetch the token.
/// It returns a [Future] that resolves when the connection is setup.
Future<Event> connectUserWithProvider(
User user, TokenProvider tokenProvider) =>
_connectUser(user, provider: tokenProvider);
Future<OwnUser> connectUserWithProvider(
User user,
TokenProvider tokenProvider, {
bool connectWebSocket = true,
}) =>
_connectUser(
user,
provider: tokenProvider,
connectWebSocket: connectWebSocket,
);
/// Connects the current user with an anonymous id, this triggers a connection
/// to the API. It returns a [Future] that resolves when the connection is
/// setup.
Future<Event> connectAnonymousUser() async {
Future<OwnUser> connectAnonymousUser({
bool connectWebSocket = true,
}) async {
final token = Token.anonymous();
final user = OwnUser(id: token.userId);
return _connectUser(user, token: token);
return _connectUser(
user,
token: token,
connectWebSocket: connectWebSocket,
);
}
/// Connects the current user as guest, this triggers a connection to the API.
/// It returns a [Future] that resolves when the connection is setup.
Future<Event> connectGuestUser(User user) async {
Future<OwnUser> connectGuestUser(
User user, {
bool connectWebSocket = true,
}) async {
final userId = user.id;
final anonymousToken = Token.anonymous(userId: userId);
@@ -253,13 +279,18 @@ class StreamChatClient {
_tokenManager.reset();
final guestUserToken = Token.fromRawValue(guestUser.accessToken);
return _connectUser(guestUser.user, token: guestUserToken);
return _connectUser(
guestUser.user,
token: guestUserToken,
connectWebSocket: connectWebSocket,
);
}
Future<Event> _connectUser(
Future<OwnUser> _connectUser(
User user, {
Token? token,
TokenProvider? provider,
bool connectWebSocket = true,
}) async {
if (_ws.connectionCompleter?.isCompleted == false) {
throw const StreamChatError(
@@ -268,7 +299,7 @@ class StreamChatClient {
);
}
logger.info('connecting user : ${user.id}');
logger.info('setting user : ${user.id}');
await _tokenManager.setTokenOrProvider(
user.id,
@@ -279,17 +310,21 @@ class StreamChatClient {
final ownUser = OwnUser.fromUser(user);
state.user = ownUser;
if (!connectWebSocket) {
return ownUser;
}
try {
if (_originalChatPersistenceClient != null) {
_chatPersistenceClient = _originalChatPersistenceClient;
await _chatPersistenceClient!.connect(ownUser.id);
}
final event = await openConnection();
return event;
final res = await openConnection();
return res;
} catch (e, stk) {
if (e is StreamWebSocketError && e.isRetriable) {
final event = await _chatPersistenceClient?.getConnectionInfo();
if (event != null) return event;
if (event != null) return event.me?.merge(ownUser) ?? ownUser;
}
logger.severe('error connecting user : ${ownUser.id}', e, stk);
rethrow;
@@ -297,7 +332,7 @@ class StreamChatClient {
}
/// Creates a new WebSocket connection with the current user.
Future<Event> openConnection() async {
Future<OwnUser> openConnection() async {
assert(
state.user != null,
'User is not set on client, '
@@ -327,7 +362,8 @@ class StreamChatClient {
_ws.connectionStatusStream.skip(1).listen(_connectionStatusHandler);
try {
return await _ws.connect(user);
final event = await _ws.connect(user);
return event.me?.merge(user) ?? user;
} catch (e, stk) {
logger.severe('error connecting ws', e, stk);
rethrow;
@@ -390,7 +426,10 @@ class StreamChatClient {
await queryChannelsOnline(
filter: Filter.in_('cid', cids),
paginationParams: const PaginationParams(limit: 30),
).then((_) => sync(cids: cids, lastSyncAt: _lastSyncedAt));
);
if (persistenceEnabled) {
await sync(cids: cids, lastSyncAt: _lastSyncedAt);
}
}
handleEvent(Event(
type: EventType.connectionRecovered,
@@ -3,6 +3,7 @@ import 'package:stream_chat/src/core/models/device.dart';
import 'package:stream_chat/src/core/models/mute.dart';
import 'package:stream_chat/src/core/models/user.dart';
import 'package:stream_chat/src/core/util/serializer.dart';
import 'package:stream_chat/stream_chat.dart';
part 'own_user.g.dart';
@@ -25,6 +26,7 @@ class OwnUser extends User {
bool online = false,
Map<String, Object?> extraData = const {},
bool banned = false,
List<String> teams = const [],
}) : super(
id: id,
role: role,
@@ -34,6 +36,7 @@ class OwnUser extends User {
online: online,
extraData: extraData,
banned: banned,
teams: teams,
);
/// Create a new instance from a json
@@ -50,8 +53,69 @@ class OwnUser extends User {
online: user.online,
banned: user.banned,
extraData: user.extraData,
teams: user.teams,
);
/// Creates a copy of [OwnUser] with specified attributes overridden.
@override
OwnUser copyWith({
String? id,
String? role,
DateTime? createdAt,
DateTime? updatedAt,
DateTime? lastActive,
bool? online,
Map<String, Object?>? extraData,
bool? banned,
List<String>? teams,
List<Mute>? channelMutes,
List<Device>? devices,
List<Mute>? mutes,
int? totalUnreadCount,
int? unreadChannels,
}) =>
OwnUser(
id: id ?? this.id,
banned: banned ?? this.banned,
role: role ?? this.role,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
lastActive: lastActive ?? this.lastActive,
online: online ?? this.online,
extraData: extraData ?? this.extraData,
teams: teams ?? this.teams,
channelMutes: channelMutes ?? this.channelMutes,
devices: devices ?? this.devices,
mutes: mutes ?? this.mutes,
totalUnreadCount: totalUnreadCount ?? this.totalUnreadCount,
unreadChannels: unreadChannels ?? this.unreadChannels,
);
/// Returns a new [OwnUser] that is a combination of this ownUser
/// and the given [other] ownUser.
OwnUser merge(OwnUser? other) {
if (other == null) {
return this;
}
return copyWith(
banned: other.banned,
channelMutes: other.channelMutes,
createdAt: other.createdAt,
devices: other.devices,
extraData: other.extraData,
id: other.id,
lastActive: other.lastActive,
mutes: other.mutes,
online: other.online,
role: other.role,
teams: other.teams,
totalUnreadCount: other.totalUnreadCount,
unreadChannels: other.unreadChannels,
updatedAt: other.updatedAt,
);
}
/// List of user devices
@JsonKey(includeIfNull: false, defaultValue: <Device>[])
final List<Device> devices;
@@ -47,9 +47,10 @@ class User extends Equatable {
/// User role
@JsonKey(
includeIfNull: false,
toJson: Serializer.readOnly,
defaultValue: <String>[])
includeIfNull: false,
toJson: Serializer.readOnly,
defaultValue: <String>[],
)
final List<String> teams;
/// Date of user creation
@@ -13,6 +13,7 @@ export './src/core/api/attachment_file_uploader.dart'
export './src/core/api/requests.dart';
export './src/core/api/requests.dart';
export './src/core/api/responses.dart';
export './src/core/api/stream_chat_api.dart' show PushProvider;
export './src/core/error/error.dart';
export './src/core/models/action.dart';
export './src/core/models/attachment.dart';
+1 -1
View File
@@ -3,4 +3,4 @@ import 'package:stream_chat/src/client/client.dart';
/// Current package version
/// Used in [StreamChatClient] to build the `x-stream-client` header
// ignore: constant_identifier_names
const PACKAGE_VERSION = '2.0.0-nullsafety.7';
const PACKAGE_VERSION = '2.0.0';
+1 -1
View File
@@ -1,7 +1,7 @@
name: stream_chat
homepage: https://getstream.io/
description: The official Dart client for Stream Chat, a service for building chat applications.
version: 2.0.0-nullsafety.7
version: 2.0.0
repository: https://github.com/GetStream/stream-chat-flutter
issue_tracker: https://github.com/GetStream/stream-chat-flutter/issues
@@ -555,7 +555,7 @@ void main() {
});
test(
'should directly update the state with message as deleted if the state is sending or failed',
'''should directly update the state with message as deleted if the state is sending or failed''',
() async {
const messageId = 'test-message-id';
final message = Message(
@@ -981,7 +981,7 @@ void main() {
);
test(
'should override previous reaction if present and `enforceUnique` is true',
'''should override previous reaction if present and `enforceUnique` is true''',
() async {
const userId = 'test-user-id';
const messageId = 'test-message-id';
@@ -1875,7 +1875,7 @@ void main() {
});
test(
'should send `typingStart` event if there is not already a typingEvent or the difference between the two is >= 2 seconds',
'''should send `typingStart` event if there is not already a typingEvent or the difference between the two is >= 2 seconds''',
() async {
final typingEvent = Event(type: EventType.typingStart);
@@ -47,12 +47,6 @@ void main() {
final user = User(id: 'test-user-id');
final token = Token.development(user.id).rawValue;
final event = Event(
type: EventType.healthCheck,
connectionId: 'fake-connection-id',
me: OwnUser.fromUser(user),
);
expectLater(
// skipping first seed status -> ConnectionStatus.disconnected
client.wsConnectionStatusStream.skip(1),
@@ -64,9 +58,7 @@ void main() {
final res = await client.connectUser(user, token);
expect(res, isNotNull);
expect(res.type, event.type);
expect(res.connectionId, event.connectionId);
expect(res.me, isSameUserAs(user));
expect(res, isSameUserAs(user));
});
test('`.connectUserWithProvider` should work fine', () async {
@@ -76,12 +68,6 @@ void main() {
return Token.development(userId).rawValue;
}
final event = Event(
type: EventType.healthCheck,
connectionId: 'fake-connection-id',
me: OwnUser.fromUser(user),
);
expectLater(
// skipping first seed status -> ConnectionStatus.disconnected
client.wsConnectionStatusStream.skip(1),
@@ -93,9 +79,7 @@ void main() {
final res = await client.connectUserWithProvider(user, tokenProvider);
expect(res, isNotNull);
expect(res.type, event.type);
expect(res.connectionId, event.connectionId);
expect(res.me, isSameUserAs(user));
expect(res, isSameUserAs(user));
});
group('`.connectGuestUser`', () {
@@ -110,12 +94,6 @@ void main() {
..accessToken = token,
);
final event = Event(
type: EventType.healthCheck,
connectionId: 'fake-connection-id',
me: OwnUser.fromUser(user),
);
expectLater(
// skipping first seed status -> ConnectionStatus.disconnected
client.wsConnectionStatusStream.skip(1),
@@ -127,9 +105,7 @@ void main() {
final res = await client.connectGuestUser(user);
expect(res, isNotNull);
expect(res.type, event.type);
expect(res.connectionId, event.connectionId);
expect(res.me, isSameUserAs(user));
expect(res, isSameUserAs(user));
verify(
() => api.guest.getGuestUser(any(that: isSameUserAs(user))),
@@ -175,9 +151,6 @@ void main() {
final res = await client.connectAnonymousUser();
expect(res, isNotNull);
expect(res.type, EventType.healthCheck);
expect(res.connectionId, 'fake-connection-id');
expect(res.me, isNotNull);
});
group('`.openConnection`', () {
@@ -330,6 +303,93 @@ void main() {
);
});
group('Connect user calls with `connectWebSocket`: false', () {
const apiKey = 'test-api-key';
late final api = FakeChatApi();
late StreamChatClient client;
setUpAll(() {
// fallback values
registerFallbackValue<User>(FakeUser());
});
setUp(() {
client = StreamChatClient(apiKey, chatApi: api);
});
tearDown(() {
client.dispose();
});
test('`.connectUser` should succeed without connecting', () async {
final user = User(id: 'test-user-id');
final token = Token.development(user.id).rawValue;
final res = await client.connectUser(
user,
token,
connectWebSocket: false,
);
expect(res, isSameUserAs(user));
expect(client.wsConnectionStatus, ConnectionStatus.disconnected);
});
test(
'`.connectUserWithProvider` should succeed without connecting',
() async {
final user = User(id: 'test-user-id');
Future<String> tokenProvider(String userId) async {
expect(userId, user.id);
return Token.development(userId).rawValue;
}
final res = await client.connectUserWithProvider(
user,
tokenProvider,
connectWebSocket: false,
);
expect(res, isSameUserAs(user));
expect(client.wsConnectionStatus, ConnectionStatus.disconnected);
},
);
test('`.connectGuestUser` should succeed without connecting', () async {
final user = User(id: 'test-user-id');
final token = Token.development(user.id).rawValue;
when(() => api.guest.getGuestUser(any(that: isSameUserAs(user))))
.thenAnswer(
(_) async => ConnectGuestUserResponse()
..user = user
..accessToken = token,
);
final res = await client.connectGuestUser(
user,
connectWebSocket: false,
);
expect(res, isSameUserAs(user));
expect(client.wsConnectionStatus, ConnectionStatus.disconnected);
verify(
() => api.guest.getGuestUser(any(that: isSameUserAs(user))),
).called(1);
});
test(
'`.connectAnonymousUser` should succeed without connecting',
() async {
final res = await client.connectAnonymousUser(
connectWebSocket: false,
);
expect(res, isNotNull);
expect(client.wsConnectionStatus, ConnectionStatus.disconnected);
},
);
});
group('Fake web-socket connection function with failure and persistence', () {
const apiKey = 'test-api-key';
late final api = FakeChatApi();
@@ -353,7 +413,7 @@ void main() {
});
test(
'`.connectUser` should connect successfully if persistence contains event',
'''`.connectUser` should connect successfully if persistence contains event''',
() async {
final user = User(id: 'test-user-id');
final token = Token.development(user.id).rawValue;
@@ -366,8 +426,7 @@ void main() {
final res = await client.connectUser(user, token);
expect(res, isNotNull);
expect(res.connectionId, 'test-connection-id');
expect(res.me?.id, user.id);
expect(res, isSameUserAs(user));
verify(persistence.getConnectionInfo).called(1);
verifyNoMoreInteractions(persistence);
@@ -375,7 +434,7 @@ void main() {
);
test(
'`.connectUserWithProvider` should connect successfully if persistence contains event',
'''`.connectUserWithProvider` should connect successfully if persistence contains event''',
() async {
final user = User(id: 'test-user-id');
Future<String> tokenProvider(String userId) async {
@@ -391,8 +450,7 @@ void main() {
final res = await client.connectUserWithProvider(user, tokenProvider);
expect(res, isNotNull);
expect(res.connectionId, 'test-connection-id');
expect(res.me?.id, user.id);
expect(res, isSameUserAs(user));
verify(persistence.getConnectionInfo).called(1);
verifyNoMoreInteractions(persistence);
@@ -400,7 +458,7 @@ void main() {
);
test(
'`.connectGuestUser` should connect successfully if persistence contains event',
'''`.connectGuestUser` should connect successfully if persistence contains event''',
() async {
final user = User(id: 'test-user-id');
final token = Token.development(user.id).rawValue;
@@ -420,8 +478,7 @@ void main() {
final res = await client.connectGuestUser(user);
expect(res, isNotNull);
expect(res.connectionId, 'test-connection-id');
expect(res.me?.id, user.id);
expect(res, isSameUserAs(user));
verify(persistence.getConnectionInfo).called(1);
verifyNoMoreInteractions(persistence);
@@ -432,7 +489,7 @@ void main() {
);
test(
'`.connectAnonymousUser` should connect successfully if persistence contains event',
'''`.connectAnonymousUser` should connect successfully if persistence contains event''',
() async {
final user = User(id: 'test-user-id');
@@ -446,8 +503,6 @@ void main() {
final res = await client.connectAnonymousUser();
expect(res, isNotNull);
expect(res.connectionId, 'test-connection-id');
expect(res.me?.id, user.id);
verify(persistence.getConnectionInfo).called(1);
verifyNoMoreInteractions(persistence);
@@ -488,7 +543,7 @@ void main() {
group('`.sync`', () {
test(
'should update persistence connectionInfo and lastSync when sync succeeds',
'''should update persistence connectionInfo and lastSync when sync succeeds''',
() async {
const cids = ['test-cid-1', 'test-cid-2', 'test-cid-3'];
final lastSyncAt = DateTime.now();
@@ -662,7 +717,7 @@ void main() {
);
test(
'should never rethrow network call if persistence already emitted some channels',
'''should never rethrow network call if persistence already emitted some channels''',
() async {
final persistentChannelStates = List.generate(
3,
@@ -870,7 +925,7 @@ void main() {
});
test(
'should rethrow if `.queryChannelsOnline` throws and persistence channels are empty',
'''should rethrow if `.queryChannelsOnline` throws and persistence channels are empty''',
() async {
when(() => api.channel.queryChannels(
filter: any(named: 'filter'),
@@ -57,7 +57,7 @@ void main() {
});
test(
'connectionIdInterceptor should be added if connectionIdManager is provided',
'''connectionIdInterceptor should be added if connectionIdManager is provided''',
() {
const apiKey = 'api-key';
final client = StreamHttpClient(
@@ -45,7 +45,7 @@ void main() {
});
test(
'`setTokenOrProvider` should throw if both token and provider is not provided',
'''`setTokenOrProvider` should throw if both token and provider is not provided''',
() async {
expect(tokenManager.userId, isNull);
@@ -192,7 +192,7 @@ void main() {
test('custom with no operator', () {
const key = 'testKey';
const values = ['testValue'];
final filter = Filter.custom(key: key, value: values);
const filter = Filter.custom(key: key, value: values);
final encoded = json.encode(filter);
expect(
encoded,
@@ -41,5 +41,43 @@ void main() {
expect(ownUser.banned, user.banned);
expect(ownUser.extraData, user.extraData);
});
test('copyWith', () {
final user = OwnUser.fromJson(jsonFixture('own_user.json'));
var newUser = user.copyWith();
expect(newUser.id, user.id);
expect(newUser.role, user.role);
expect(newUser.name, user.name);
newUser = user.copyWith(
id: 'test',
role: 'test',
extraData: {
'name': 'test',
},
);
expect(newUser.id, 'test');
expect(newUser.role, 'test');
expect(newUser.name, 'test');
});
test('merge', () {
final user = OwnUser.fromJson(jsonFixture('own_user.json'));
final newUser = user.merge(OwnUser(
id: 'test',
role: 'test',
extraData: const {
'name': 'test',
},
banned: true,
));
expect(newUser.id, 'test');
expect(newUser.role, 'test');
expect(newUser.name, 'test');
expect(newUser.banned, true);
});
});
}
@@ -13,7 +13,7 @@ void main() {
expect(reaction.type, 'wow');
expect(
reaction.user?.toJson(),
User(id: '2de0297c-f3f2-489d-b930-ef77342edccf', extraData: {
User(id: '2de0297c-f3f2-489d-b930-ef77342edccf', extraData: const {
'image': 'https://randomuser.me/api/portraits/women/45.jpg',
'name': 'Daisy Morgan'
}).toJson(),
@@ -28,7 +28,8 @@ void main() {
messageId: '76cd8c82-b557-4e48-9d12-87995d3a0e04',
createdAt: DateTime.parse('2020-01-28T22:17:31.108742Z'),
type: 'wow',
user: User(id: '2de0297c-f3f2-489d-b930-ef77342edccf', extraData: {
user:
User(id: '2de0297c-f3f2-489d-b930-ef77342edccf', extraData: const {
'image': 'https://randomuser.me/api/portraits/women/45.jpg',
'name': 'Daisy Morgan'
}),
@@ -154,7 +154,6 @@ void main() {
});
test('updateChannelState', () async {
const cid = 'test:cid';
final channelState = ChannelState();
persistenceClient.updateChannelState(channelState);
});
+85
View File
@@ -1,3 +1,88 @@
## 2.0.0
🛑️ Breaking Changes from `1.5.4`
- Migrate this package to null safety
- Renamed `ChannelImage` to `ChannelAvatar`
- Updated `StreamChatThemeData.reactionIcons` to accept custom builder
- Renamed `ColorTheme` properties to reflect the purpose of the colors
- `ColorTheme.black` -> `ColorTheme.textHighEmphasis`
- `ColorTheme.grey` -> `ColorTheme.textLowEmphasis`
- `ColorTheme.greyGainsboro` -> `ColorTheme.disabled`
- `ColorTheme.greyWhisper` -> `ColorTheme.borders`
- `ColorTheme.whiteSmoke` -> `ColorTheme.inputBg`
- `ColorTheme.whiteSnow` -> `ColorTheme.appBg`
- `ColorTheme.white` -> `ColorTheme.barsBg`
- `ColorTheme.blueAlice` -> `ColorTheme.linkBg`
- `ColorTheme.accentBlue` -> `ColorTheme.accentPrimary`
- `ColorTheme.accentRed` -> `ColorTheme.accentError`
- `ColorTheme.accentGreen` -> `ColorTheme.accentInfo`
- `ChannelListCore` options property is removed in favor of individual properties
- `options.state` -> bool state
- `options.watch` -> bool watch
- `options.presence` -> bool presence
- `UserListView` options property is removed in favor of individual properties
- `options.presence` -> bool presence
- Renamed `ImageHeader` to `GalleryHeader`
- Renamed `ImageFooter` to `GalleryFooter`
- `MessageBuilder` and `ParentMessageBuilder` signature is now
```dart
typedef MessageBuilder = Widget Function(
BuildContext,
MessageDetails,
List<Message>,
MessageWidget defaultMessageWidget,
);
```
the last parameter is the default `MessageWidget`
You can call `.copyWith` to customize just a subset of properties
✅ Added
- Added video compress options (frame and quality) to `MessageInput`
- TypingIndicator now has a property called `parentId` to show typing indicator specific to threads
- [#493](https://github.com/GetStream/stream-chat-flutter/pull/493): add support for messageListView header/footer
- `MessageWidget` accepts a `userAvatarBuilder`
- Added pinMessage ui support
- Added `MessageListView.threadSeparatorBuilder` property
- Added `MessageInput.onError` property to allow error handling
- Added `GalleryHeader/GalleryFooter` theme classes
🐞 Fixed
- [#483](https://github.com/GetStream/stream-chat-flutter/issues/483): Keyboard covers input text box when editing
message
- Modals are shown using the nearest `Navigator` to make using the SDK easier in a nested navigator use case
- [#484](https://github.com/GetStream/stream-chat-flutter/issues/484): messages don't update without a reload
- `MessageListView` not rendering if the user is not a member of the channel
- Fix `MessageInput` overflow when there are no actions
- Minor fixes and improvements
## 2.0.0-nullsafety.9
🛑️ Breaking Changes from `2.0.0-nullsafety.8`
- Renamed `ColorTheme` properties to reflect the purpose of the colors
- `ColorTheme.black` -> `ColorTheme.textHighEmphasis`
- `ColorTheme.grey` -> `ColorTheme.textLowEmphasis`
- `ColorTheme.greyGainsboro` -> `ColorTheme.disabled`
- `ColorTheme.greyWhisper` -> `ColorTheme.borders`
- `ColorTheme.whiteSmoke` -> `ColorTheme.inputBg`
- `ColorTheme.whiteSnow` -> `ColorTheme.appBg`
- `ColorTheme.white` -> `ColorTheme.barsBg`
- `ColorTheme.blueAlice` -> `ColorTheme.linkBg`
- `ColorTheme.accentBlue` -> `ColorTheme.accentPrimary`
- `ColorTheme.accentRed` -> `ColorTheme.accentError`
- `ColorTheme.accentGreen` -> `ColorTheme.accentInfo`
✅ Added
- Added video compress options (frame and quality) to `MessageInput`
## 2.0.0-nullsafety.8
🛑️ Breaking Changes from `2.0.0-nullsafety.7`
+1 -1
View File
@@ -28,7 +28,7 @@ It teaches you how to use this SDK and also shows how to make frequently require
## Example App
This repo includes a fully functional example app with setup instructions.
The example is available under the [example](https://github.com/GetStream/stream-chat-flutter/tree/master/example) folder.
The example is available under the [example](https://github.com/GetStream/stream-chat-flutter/tree/master/packages/stream_chat_flutter/example) folder.
## Add dependency
Add this to your package's pubspec.yaml file, use the latest version [![Pub](https://img.shields.io/pub/v/stream_chat_flutter.svg)](https://pub.dartlang.org/packages/stream_chat_flutter)
@@ -34,84 +34,96 @@ class _HindiStreamChatLocalizationsDelegate
void main() async {
WidgetsFlutterBinding.ensureInitialized();
/// Create a new instance of [StreamChatClient] passing the apikey obtained from your
/// project dashboard.
/// Create a new instance of [StreamChatClient] passing the apikey obtained
/// from your project dashboard.
final client = StreamChatClient(
's2dxdhpxd94g',
logLevel: Level.INFO,
);
/// Set the current user and connect the websocket. In a production scenario, this should be done using
/// a backend to generate a user token using our server SDK.
/// Set the current user and connect the websocket. In a production
/// scenario, this should be done using a backend to generate a user token
/// using our server SDK.
///
/// Please see the following for more information:
/// https://getstream.io/chat/docs/ios_user_setup_and_tokens/
await client.connectUser(
User(id: 'super-band-9'),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A',
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.'
'0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A',
);
final channel = client.channel('messaging', id: 'godevs');
await channel.watch();
runApp(MyApp(client, channel));
runApp(
MyApp(
client: client,
channel: channel,
),
);
}
/// Example application using Stream Chat Flutter widgets.
/// Stream Chat Flutter is a set of Flutter widgets which provide full chat functionalities
/// for building Flutter applications using Stream.
/// If you'd prefer using minimal wrapper widgets for your app, please see our other
///
/// Stream Chat Flutter is a set of Flutter widgets which provide full chat
/// functionalities for building Flutter applications using Stream. If you'd
/// prefer using minimal wrapper widgets for your app, please see our other
/// package, `stream_chat_flutter_core`.
class MyApp extends StatelessWidget {
/// Example using Stream's Flutter package.
///
/// If you'd prefer using minimal wrapper widgets for your app, please see
/// our other package, `stream_chat_flutter_core`.
const MyApp({
Key? key,
required this.client,
required this.channel,
}) : super(key: key);
/// Instance of Stream Client.
/// Stream's [StreamChatClient] can be used to connect to our servers and set the default
/// user for the application. Performing these actions trigger a websocket connection
/// allowing for real-time updates.
///
/// Stream's [StreamChatClient] can be used to connect to our servers and
/// set the default user for the application. Performing these actions
/// trigger a websocket connection allowing for real-time updates.
final StreamChatClient client;
/// Instance of the Channel
final Channel channel;
/// Example using Stream's Flutter package.
/// If you'd prefer using minimal wrapper widgets for your app, please see our other
/// package, `stream_chat_flutter_core`.
MyApp(this.client, this.channel);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: ThemeMode.system,
supportedLocales: [
Locale('en', 'US'),
Locale('hi', 'IN'),
],
localizationsDelegates: [
GlobalStreamChatLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
StreamChatLocalizationsHi.delegate,
],
builder: (context, widget) {
return StreamChat(
Widget build(BuildContext context) => MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: ThemeMode.system,
supportedLocales: [
Locale('en', 'US'),
Locale('hi', 'IN'),
],
localizationsDelegates: [
GlobalStreamChatLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
StreamChatLocalizationsHi.delegate,
],
builder: (context, widget) => StreamChat(
client: client,
child: widget,
);
},
home: StreamChannel(
channel: channel,
child: ChannelPage(),
),
);
}
),
home: StreamChannel(
channel: channel,
child: const ChannelPage(),
),
);
}
/// A list of messages sent in the current channel.
///
/// This is implemented using [MessageListView], a widget that provides query functionalities
/// fetching the messages from the api and showing them in a listView
/// This is implemented using [MessageListView], a widget that provides query
/// functionalities fetching the messages from the api and showing them in a
/// listView.
class ChannelPage extends StatelessWidget {
/// Creates the page that shows the list of messages
const ChannelPage({
@@ -119,17 +131,15 @@ class ChannelPage extends StatelessWidget {
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
body: Column(
children: <Widget>[
Expanded(
child: MessageListView(),
),
MessageInput(),
],
),
);
}
Widget build(BuildContext context) => Scaffold(
appBar: const ChannelHeader(),
body: Column(
children: const <Widget>[
Expanded(
child: MessageListView(),
),
MessageInput(),
],
),
);
}
@@ -10,30 +10,39 @@ void main() async {
await client.connectUser(
User(id: 'super-band-9'),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A',
'''eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A''',
);
runApp(MyApp(client));
runApp(
MyApp(
client: client,
),
);
}
class MyApp extends StatelessWidget {
const MyApp({
Key? key,
required this.client,
}) : super(key: key);
final StreamChatClient client;
MyApp(this.client);
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) => StreamChat(
client: client,
child: child,
),
home: SplitView(),
);
}
Widget build(BuildContext context) => MaterialApp(
builder: (context, child) => StreamChat(
client: client,
child: child,
),
home: const SplitView(),
);
}
class SplitView extends StatefulWidget {
const SplitView({
Key? key,
}) : super(key: key);
@override
_SplitViewState createState() => _SplitViewState();
}
@@ -42,69 +51,67 @@ class _SplitViewState extends State<SplitView> {
Channel? selectedChannel;
@override
Widget build(BuildContext context) {
return Flex(
direction: Axis.horizontal,
children: <Widget>[
Flexible(
flex: 1,
child: ChannelListPage(
onTap: (channel) {
setState(() {
selectedChannel = channel;
});
},
Widget build(BuildContext context) => Flex(
direction: Axis.horizontal,
children: <Widget>[
Flexible(
child: ChannelListPage(
onTap: (channel) {
setState(() {
selectedChannel = channel;
});
},
),
),
),
Flexible(
flex: 2,
child: Scaffold(
body: selectedChannel != null
? StreamChannel(
key: ValueKey(selectedChannel!.cid),
channel: selectedChannel!,
child: ChannelPage(),
)
: Center(
child: Text(
'Pick a channel to show the messages 💬',
style: Theme.of(context).textTheme.headline5,
Flexible(
flex: 2,
child: Scaffold(
body: selectedChannel != null
? StreamChannel(
key: ValueKey(selectedChannel!.cid),
channel: selectedChannel!,
child: const ChannelPage(),
)
: Center(
child: Text(
'Pick a channel to show the messages 💬',
style: Theme.of(context).textTheme.headline5,
),
),
),
),
),
),
],
);
}
],
);
}
class ChannelListPage extends StatelessWidget {
const ChannelListPage({
Key? key,
this.onTap,
}) : super(key: key);
final void Function(Channel)? onTap;
ChannelListPage({this.onTap});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ChannelsBloc(
child: ChannelListView(
onChannelTap: onTap != null
? (channel, _) {
onTap!(channel);
}
: null,
filter: Filter.in_(
'members',
[StreamChat.of(context).user!.id],
),
sort: [SortOption('last_message_at')],
pagination: PaginationParams(
limit: 20,
Widget build(BuildContext context) => Scaffold(
body: ChannelsBloc(
child: ChannelListView(
onChannelTap: onTap != null
? (channel, _) {
onTap!(channel);
}
: null,
filter: Filter.in_(
'members',
[StreamChat.of(context).user!.id],
),
sort: const [SortOption('last_message_at')],
pagination: const PaginationParams(
limit: 20,
),
),
),
),
);
}
);
}
class ChannelPage extends StatelessWidget {
@@ -113,27 +120,21 @@ class ChannelPage extends StatelessWidget {
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Navigator(
onGenerateRoute: (settings) {
return MaterialPageRoute(
builder: (context) {
return Scaffold(
appBar: ChannelHeader(
showBackButton: false,
),
body: Column(
children: <Widget>[
Expanded(
child: MessageListView(),
),
MessageInput(),
],
),
);
},
);
},
);
}
Widget build(BuildContext context) => Navigator(
onGenerateRoute: (settings) => MaterialPageRoute(
builder: (context) => Scaffold(
appBar: const ChannelHeader(
showBackButton: false,
),
body: Column(
children: const <Widget>[
Expanded(
child: MessageListView(),
),
MessageInput(),
],
),
),
),
);
}
@@ -4,25 +4,30 @@ import 'package:stream_chat_flutter/stream_chat_flutter.dart';
/// First step of the [tutorial](https://getstream.io/chat/flutter/tutorial/)
///
/// There are three important things to notice that are common to all Flutter application using StreamChat:
/// There are three important things to notice that are common to all Flutter
/// application using StreamChat:
///
/// 1. The Dart API [StreamChatClient] is initialized with your API Key
/// 2. The current user is set by calling [StreamChatClient.connectUser]
/// 3. The client is then passed to the top-level [StreamChat] widget
/// [StreamChat] is an inherited widget and must be the parent of all Chat related widgets.
/// [StreamChat] is an inherited widget and must be the parent of all
/// Chat related widgets.
///
/// Please note that while Flutter can be used to build both mobile and web applications;
/// in this tutorial we focus on mobile, make sure when running the app you use a mobile device.
/// Please note that while Flutter can be used to build both mobile and web
/// applications, in this tutorial we focus on mobile. Make sure when running
/// the app that you use a mobile device.
///
/// Let's have a look at what we've built:
///
/// - We set up the Chat [StreamChatClient] with the API key
///
/// - We set the the current user for Chat with [StreamChatClient.connectUser] and a pre-generated user token
/// - We set the the current user for Chat with [StreamChatClient.connectUser]
/// and a pre-generated user token
///
/// - We make [StreamChat] the root Widget of our application
///
/// - We create a single [ChannelPage] widget under [StreamChat] with three widgets: [ChannelHeader], [MessageListView] and [MessageInput]
/// - We create a single [ChannelPage] widget under [StreamChat] with three
/// widgets: [ChannelHeader], [MessageListView] and [MessageInput]
///
/// If you now run the simulator you will see a single channel UI.
void main() async {
@@ -33,26 +38,38 @@ void main() async {
await client.connectUser(
User(id: 'super-band-9'),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A',
'''eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A''',
);
final channel = client.channel('messaging', id: 'godevs');
// ignore: unawaited_futures
// ignore: unawaited_futures, cascade_invocations
channel.watch();
runApp(MyApp(client, channel));
runApp(
MyApp(
client: client,
channel: channel,
),
);
}
class MyApp extends StatelessWidget {
const MyApp({
Key? key,
required this.client,
required this.channel,
}) : super(key: key);
final StreamChatClient client;
final Channel channel;
MyApp(this.client, this.channel);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return MaterialApp(
// ignore: prefer_expression_function_bodies
builder: (context, widget) {
return StreamChat(
client: client,
@@ -61,7 +78,7 @@ class MyApp extends StatelessWidget {
},
home: StreamChannel(
channel: channel,
child: ChannelPage(),
child: const ChannelPage(),
),
);
}
@@ -73,11 +90,12 @@ class ChannelPage extends StatelessWidget {
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
appBar: const ChannelHeader(),
body: Column(
children: <Widget>[
children: const <Widget>[
Expanded(
child: MessageListView(),
),
@@ -5,20 +5,29 @@ import 'package:stream_chat_flutter/stream_chat_flutter.dart';
/// Second step of the [tutorial](https://getstream.io/chat/flutter/tutorial/)
///
/// Most chat applications handle more than just one single conversation.
/// Apps like Facebook Messenger, Whatsapp and Telegram allows you to have multiple one to one and group conversations.
/// Apps like Facebook Messenger, Whatsapp and Telegram allows you to have
/// multiple one-to-one and group conversations.
///
/// Lets find out how we can change our application chat screen to display the list of conversations and navigate between them.
/// Lets find out how we can change our application chat screen to display
/// the list of conversations and navigate between them.
///
/// > Note: the SDK uses Flutters [Navigator] to move from one route to another, this allows us to avoid any boiler-plate code.
/// > Of course you can take total control of how navigation works by customizing widgets like [Channel] and [ChannelList].
/// > Note: the SDK uses Flutters [Navigator] to move from one route to
/// another. This allows us to avoid any boiler-plate code.
/// > Of course, you can take total control of how navigation works by
/// customizing widgets like [Channel] and [ChannelList].
///
/// If you run the application, you will see that the first screen shows a list of conversations, you can open each by tapping and go back to the list.
/// If you run the application, you will see that the first screen shows a
/// list of conversations, you can open each by tapping and go back to the list.
///
/// Every single widget involved in this UI can be customized or swapped with your own.
/// Every single widget involved in this UI can be customized or swapped
/// with your own.
///
/// The [ChannelListPage] widget retrieves the list of channels based on a custom query and ordering.
/// In this case we are showing the list of channels the current user is a member and we order them based on the time they had a new message.
/// [ChannelListView] handles pagination and updates automatically out of the box when new channels are created or when a new message is added to a channel.
/// The [ChannelListPage] widget retrieves the list of channels based on a
/// custom query and ordering. In this case we are showing the list of
/// channels in which the current user is a member and we order them based
/// on the time they had a new message. [ChannelListView] handles pagination
/// and updates automatically when new channels are created or when a new
/// message is added to a channel.
void main() async {
final client = StreamChatClient(
's2dxdhpxd94g',
@@ -27,31 +36,44 @@ void main() async {
await client.connectUser(
User(id: 'super-band-9'),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A',
'''eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A''',
);
runApp(MyApp(client));
runApp(
MyApp(
client: client,
),
);
}
class MyApp extends StatelessWidget {
const MyApp({
Key? key,
required this.client,
}) : super(key: key);
final StreamChatClient client;
MyApp(this.client);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) => StreamChat(
client: client,
child: child,
),
home: ChannelListPage(),
home: const ChannelListPage(),
);
}
}
class ChannelListPage extends StatelessWidget {
const ChannelListPage({
Key? key,
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
body: ChannelsBloc(
@@ -60,11 +82,11 @@ class ChannelListPage extends StatelessWidget {
'members',
[StreamChat.of(context).user!.id],
),
sort: [SortOption('last_message_at')],
pagination: PaginationParams(
sort: const [SortOption('last_message_at')],
pagination: const PaginationParams(
limit: 20,
),
channelWidget: ChannelPage(),
channelWidget: const ChannelPage(),
),
),
);
@@ -77,11 +99,12 @@ class ChannelPage extends StatelessWidget {
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
appBar: const ChannelHeader(),
body: Column(
children: <Widget>[
children: const <Widget>[
Expanded(
child: MessageListView(),
),
@@ -6,22 +6,30 @@ import 'package:stream_chat_flutter/stream_chat_flutter.dart';
/// Third step of the [tutorial](https://getstream.io/chat/flutter/tutorial/)
///
/// So far youve learned how to use the default widgets.
/// The library has been designed with composition in mind and to allow all common customizations to be very easy.
/// This means that you can change any component in your application by swapping the default widgets with the ones you build yourself.
/// The library has been designed with composition in mind and to allow all
/// common customizations to be very easy.
/// This means that you can change any component in your application by
/// swapping the default widgets with the ones you build yourself.
///
/// Lets see how we can make some changes to the SDKs UI components.
/// We start by changing how channel previews are shown in the channel list and include the number of unread messages for each.
/// We start by changing how channel previews are shown in the channel list
/// and include the number of unread messages for each.
///
/// We're passing a custom widget to [ChannelListView.channelPreviewBuilder], this will override the default [ChannelPreview] and allows you to create one yourself.
/// We're passing a custom widget to [ChannelListView.channelPreviewBuilder];
/// this will override the default [ChannelPreview] and allows you to create
/// one yourself.
///
/// There are a couple interesting things we do in this widget:
///
/// - Instead of creating a whole new style for the channel name, we inherit the text style from the parent theme ([StreamChatTheme.of]) and only change the color attribute
/// - Instead of creating a whole new style for the channel name, we inherit
/// the text style from the parent theme ([StreamChatTheme.of]) and only
/// change the color attribute
///
/// - We loop over the list of channel messages to search for the first not deleted message ([Channel.state.messages])
/// - We loop over the list of channel messages to search for the first not
/// deleted message ([Channel.state.messages])
///
/// - We retrieve the count of unread messages from [Channel.state]
void main() async {
Future<void> main() async {
final client = StreamChatClient(
's2dxdhpxd94g',
logLevel: Level.INFO,
@@ -29,31 +37,44 @@ void main() async {
await client.connectUser(
User(id: 'super-band-9'),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A',
'''eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A''',
);
runApp(MyApp(client));
runApp(
MyApp(
client: client,
),
);
}
class MyApp extends StatelessWidget {
const MyApp({
Key? key,
required this.client,
}) : super(key: key);
final StreamChatClient client;
MyApp(this.client);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) => StreamChat(
client: client,
child: child,
),
home: ChannelListPage(),
home: const ChannelListPage(),
);
}
}
class ChannelListPage extends StatelessWidget {
const ChannelListPage({
Key? key,
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
body: ChannelsBloc(
@@ -64,10 +85,10 @@ class ChannelListPage extends StatelessWidget {
),
channelPreviewBuilder: _channelPreviewBuilder,
// sort: [SortOption('last_message_at')],
pagination: PaginationParams(
pagination: const PaginationParams(
limit: 20,
),
channelWidget: ChannelPage(),
channelWidget: const ChannelPage(),
),
),
);
@@ -78,7 +99,7 @@ class ChannelListPage extends StatelessWidget {
(message) => !message.isDeleted,
);
final subtitle = (lastMessage == null ? 'nothing yet' : lastMessage.text!);
final subtitle = lastMessage == null ? 'nothing yet' : lastMessage.text!;
final opacity = (channel.state?.unreadCount ?? 0) > 0 ? 1.0 : 0.5;
return ListTile(
@@ -88,12 +109,12 @@ class ChannelListPage extends StatelessWidget {
MaterialPageRoute(
builder: (_) => StreamChannel(
channel: channel,
child: ChannelPage(),
child: const ChannelPage(),
),
),
);
},
leading: ChannelImage(
leading: ChannelAvatar(
channel: channel,
),
title: ChannelName(
@@ -101,17 +122,17 @@ class ChannelListPage extends StatelessWidget {
StreamChatTheme.of(context).channelPreviewTheme.title!.copyWith(
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(opacity),
),
),
subtitle: Text(subtitle),
trailing: channel.state!.unreadCount! > 0
trailing: channel.state!.unreadCount > 0
? CircleAvatar(
radius: 10,
child: Text(channel.state!.unreadCount.toString()),
)
: SizedBox(),
: const SizedBox(),
);
}
}
@@ -122,11 +143,12 @@ class ChannelPage extends StatelessWidget {
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
appBar: const ChannelHeader(),
body: Column(
children: <Widget>[
children: const <Widget>[
Expanded(
child: MessageListView(),
),
@@ -4,13 +4,17 @@ import 'package:stream_chat_flutter/stream_chat_flutter.dart';
/// Fourth step of the [tutorial](https://getstream.io/chat/flutter/tutorial/)
///
/// Stream Chat supports message threads out of the box. Threads allows users to create sub-conversations inside the same channel.
/// Stream Chat supports message threads out of the box. Threads allows users
/// to create sub-conversations inside the same channel.
///
/// Using threaded conversations is very simple and mostly a matter of plugging the [MessageListView] to another widget that renders the widget.
/// To make this simple, such a widget only needs to build [MessageListView] with the parent attribute set to the threads root message.
/// Using threaded conversations is very simple and mostly a matter of
/// plugging the [MessageListView] to another widget that renders the widget.
/// To make this simple, such a widget only needs to build [MessageListView]
/// with the parent attribute set to the threads root message.
///
/// Now we can open threads and create new ones as well, if you long press a message you can tap on Reply and it will open the same [ThreadPage].
void main() async {
/// Now we can open threads and create new ones as well. If you long-press a
/// message, you can tap on "Reply" and it will open the same [ThreadPage].
Future<void> main() async {
final client = StreamChatClient(
's2dxdhpxd94g',
logLevel: Level.INFO,
@@ -18,33 +22,44 @@ void main() async {
await client.connectUser(
User(id: 'super-band-9'),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A',
'''eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A''',
);
runApp(MyApp(client));
runApp(
MyApp(
client: client,
),
);
}
class MyApp extends StatelessWidget {
const MyApp({
Key? key,
required this.client,
}) : super(key: key);
final StreamChatClient client;
MyApp(this.client);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) => StreamChat(
client: client,
child: child,
),
home: Container(
child: ChannelListPage(),
),
home: const ChannelListPage(),
);
}
}
class ChannelListPage extends StatelessWidget {
const ChannelListPage({
Key? key,
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
body: ChannelsBloc(
@@ -53,11 +68,11 @@ class ChannelListPage extends StatelessWidget {
'members',
[StreamChat.of(context).user!.id],
),
sort: [SortOption('last_message_at')],
pagination: PaginationParams(
sort: const [SortOption('last_message_at')],
pagination: const PaginationParams(
limit: 20,
),
channelWidget: ChannelPage(),
channelWidget: const ChannelPage(),
),
),
);
@@ -70,21 +85,20 @@ class ChannelPage extends StatelessWidget {
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
appBar: const ChannelHeader(),
body: Column(
children: <Widget>[
Expanded(
child: MessageListView(
threadBuilder: (_, parentMessage) {
return ThreadPage(
parent: parentMessage,
);
},
threadBuilder: (_, parentMessage) => ThreadPage(
parent: parentMessage,
),
),
),
MessageInput(),
const MessageInput(),
],
),
);
@@ -92,14 +106,15 @@ class ChannelPage extends StatelessWidget {
}
class ThreadPage extends StatelessWidget {
final Message? parent;
ThreadPage({
const ThreadPage({
Key? key,
this.parent,
}) : super(key: key);
final Message? parent;
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
appBar: ThreadHeader(
@@ -4,18 +4,23 @@ import 'package:stream_chat_flutter/stream_chat_flutter.dart';
/// Fifth step of the [tutorial](https://getstream.io/chat/flutter/tutorial/)
///
/// Customizing how messages are rendered is another very common use-case that the SDK supports easily.
/// Customizing how messages are rendered is another very common use-case that
/// the SDK supports easily.
///
/// Replace the built-in message component with your own is done by passing it as a builder function to the [MessageListView] widget.
/// Replacing the built-in message component with your own is done by passing
/// it as a builder function to the [MessageListView] widget.
///
/// The message builder function will get the usual [BuildContext] argument as well as the [Message] object and its position inside the list.
/// The message builder function will get the usual [BuildContext] argument
/// as well as the [Message] object and its position inside the list.
///
/// If you look at the code you can see that we use [StreamChat.of] to retrieve the current user so that we can style messages own messages in a different way.
/// If you look at the code you can see that we use [StreamChat.of] to
/// retrieve the current user so that we can style messages in a different way.
///
/// Since custom widgets and builders are always children of [StreamChat] or part of a [Channel],
/// you can use [StreamChat.of], [StreamChannel.of] and [StreamChatTheme.of] to use the API client directly
/// or to retrieve outer scope needed such as messages from the [Channel.state].
void main() async {
/// Since custom widgets and builders are always children of [StreamChat] or
/// part of a [Channel], you can use [StreamChat.of], [StreamChannel.of],
/// and [StreamChatTheme.of] to use the API client directly or to retrieve
/// outer scope needed such as messages from the [Channel.state].
Future<void> main() async {
final client = StreamChatClient(
's2dxdhpxd94g',
logLevel: Level.INFO,
@@ -23,31 +28,44 @@ void main() async {
await client.connectUser(
User(id: 'super-band-9'),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A',
'''eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A''',
);
runApp(MyApp(client));
runApp(
MyApp(
client: client,
),
);
}
class MyApp extends StatelessWidget {
const MyApp({
Key? key,
required this.client,
}) : super(key: key);
final StreamChatClient client;
MyApp(this.client);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) => StreamChat(
client: client,
child: child,
),
home: ChannelListPage(),
home: const ChannelListPage(),
);
}
}
class ChannelListPage extends StatelessWidget {
const ChannelListPage({
Key? key,
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
body: ChannelsBloc(
@@ -56,11 +74,11 @@ class ChannelListPage extends StatelessWidget {
'members',
[StreamChat.of(context).user!.id],
),
sort: [SortOption('last_message_at')],
pagination: PaginationParams(
sort: const [SortOption('last_message_at')],
pagination: const PaginationParams(
limit: 20,
),
channelWidget: ChannelPage(),
channelWidget: const ChannelPage(),
),
),
);
@@ -73,9 +91,10 @@ class ChannelPage extends StatelessWidget {
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
appBar: const ChannelHeader(),
body: Column(
children: <Widget>[
Expanded(
@@ -83,7 +102,7 @@ class ChannelPage extends StatelessWidget {
messageBuilder: _messageBuilder,
),
),
MessageInput(),
const MessageInput(),
],
),
);
@@ -101,12 +120,14 @@ class ChannelPage extends StatelessWidget {
final color = isCurrentUser ? Colors.blueGrey : Colors.blue;
return Padding(
padding: EdgeInsets.all(5.0),
padding: const EdgeInsets.all(5),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: color, width: 1),
borderRadius: BorderRadius.all(
Radius.circular(5.0),
border: Border.all(
color: color,
),
borderRadius: const BorderRadius.all(
Radius.circular(5),
),
),
child: ListTile(
@@ -115,7 +136,7 @@ class ChannelPage extends StatelessWidget {
textAlign: textAlign,
),
subtitle: Text(
message.user!.extraData['name'] as String,
message.user!.name,
textAlign: textAlign,
),
),
@@ -4,22 +4,29 @@ import 'package:stream_chat_flutter/stream_chat_flutter.dart';
/// Sixth step of the [tutorial](https://getstream.io/chat/flutter/tutorial/)
///
/// The Flutter SDK comes with a fully designed set of widgets which you can customize to fit with your application style and typography.
/// Changing the theme of Chat widgets works in a very similar way that [MaterialApp] and [Theme] do.
/// The Flutter SDK comes with a fully designed set of widgets which you can
/// customize to fit with your application style and typography.
/// Changing the theme of Chat widgets works in a very similar way that
/// [MaterialApp] and [Theme] do.
///
/// Out of the box all chat widgets use their own default styling, there are two ways to change the styling:
/// All chat widgets use their own default styling out of the box. There are
/// two ways to change the styling:
///
/// 1. Initialize the [StreamChatTheme] from your existing [MaterialApp] style
/// 2. Construct a custom theme and provide all the customizations needed
///
/// First we create a new Material [Theme] and pick [Colors.green] as swatch color. The theme is then passed to [MaterialApp] as usual.
/// First, we create a new Material [Theme] and pick [Colors.green] as the
/// swatch color. The theme is then passed to [MaterialApp] as usual.
///
/// Then we create a new [StreamChatTheme] from the green theme we just created.
/// After saving the app you will see the UI will update several widgets to match with the new color.
/// Then, we create a new [StreamChatTheme] from the green theme we just
/// created. After saving the app you will see that several widgets have
/// been updated with the new color.
///
/// We also change the message color posted by the current user.
/// You can perform these more granular style changes using [StreamChatTheme.copyWith].
void main() async {
///
/// You can perform these more granular style changes using
/// [StreamChatTheme.copyWith].
Future<void> main() async {
final client = StreamChatClient(
's2dxdhpxd94g',
logLevel: Level.INFO,
@@ -27,16 +34,23 @@ void main() async {
await client.connectUser(
User(id: 'super-band-9'),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A',
'''eyJ0eXAiO«iJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic3VwZXItYmFuZC05In0.0L6lGoeLwkz0aZRUcpZKsvaXtNEDHBcezVTZ0oPq40A''',
);
runApp(MyApp(client));
runApp(
MyApp(
client: client,
),
);
}
class MyApp extends StatelessWidget {
final StreamChatClient client;
const MyApp({
Key? key,
required this.client,
}) : super(key: key);
MyApp(this.client);
final StreamChatClient client;
@override
Widget build(BuildContext context) {
@@ -50,9 +64,9 @@ class MyApp extends StatelessWidget {
),
),
otherMessageTheme: MessageTheme(
messageBackgroundColor: colorTheme.black,
messageBackgroundColor: colorTheme.textHighEmphasis,
messageText: TextStyle(
color: colorTheme.white,
color: colorTheme.barsBg,
),
avatarTheme: AvatarTheme(
borderRadius: BorderRadius.circular(8),
@@ -62,20 +76,23 @@ class MyApp extends StatelessWidget {
return MaterialApp(
theme: themeData,
builder: (context, child) {
return StreamChat(
client: client,
streamChatThemeData: customTheme,
child: child,
);
},
home: ChannelListPage(),
builder: (context, child) => StreamChat(
client: client,
streamChatThemeData: customTheme,
child: child,
),
home: const ChannelListPage(),
);
}
}
class ChannelListPage extends StatelessWidget {
const ChannelListPage({
Key? key,
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
body: ChannelsBloc(
@@ -84,11 +101,11 @@ class ChannelListPage extends StatelessWidget {
'members',
[StreamChat.of(context).user!.id],
),
sort: [SortOption('last_message_at')],
pagination: PaginationParams(
sort: const [SortOption('last_message_at')],
pagination: const PaginationParams(
limit: 20,
),
channelWidget: ChannelPage(),
channelWidget: const ChannelPage(),
),
),
);
@@ -101,21 +118,20 @@ class ChannelPage extends StatelessWidget {
}) : super(key: key);
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
appBar: const ChannelHeader(),
body: Column(
children: <Widget>[
Expanded(
child: MessageListView(
threadBuilder: (_, parentMessage) {
return ThreadPage(
parent: parentMessage,
);
},
threadBuilder: (_, parentMessage) => ThreadPage(
parent: parentMessage,
),
),
),
MessageInput(),
const MessageInput(),
],
),
);
@@ -123,14 +139,15 @@ class ChannelPage extends StatelessWidget {
}
class ThreadPage extends StatelessWidget {
final Message? parent;
ThreadPage({
const ThreadPage({
Key? key,
this.parent,
}) : super(key: key);
final Message? parent;
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context) {
return Scaffold(
appBar: ThreadHeader(
@@ -21,23 +21,23 @@ environment:
sdk: '>=2.12.0 <3.0.0'
dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
collection: ^1.15.0
cupertino_icons: ^1.0.3
flutter:
sdk: flutter
# stream_chat:
# path: ../../stream_chat
# stream_chat_flutter_core:
# path: ../../stream_chat_flutter_core
# stream_chat:
# path: ../../stream_chat
# stream_chat_flutter_core:
# path: ../../stream_chat_flutter_core
stream_chat_flutter:
path: ../
stream_chat_localizations:
path: ../../stream_chat_localizations
stream_chat_persistence:
stream_chat_persistence:
path: ../../stream_chat_persistence
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
collection: ^1.15.0
dev_dependencies:
flutter_test:
@@ -35,7 +35,7 @@ class AttachmentTitle extends StatelessWidget {
attachment.title!,
overflow: TextOverflow.ellipsis,
style: messageTheme.messageText?.copyWith(
color: StreamChatTheme.of(context).colorTheme.accentBlue,
color: StreamChatTheme.of(context).colorTheme.accentPrimary,
fontWeight: FontWeight.bold,
),
),
@@ -130,7 +130,7 @@ class _PreparingState extends StatelessWidget {
alignment: Alignment.topRight,
child: _IconButton(
icon: StreamSvgIcon.close(
color: StreamChatTheme.of(context).colorTheme.white,
color: StreamChatTheme.of(context).colorTheme.barsBg,
),
onPressed: () => channel.cancelAttachmentUpload(attachmentId),
),
@@ -170,7 +170,7 @@ class _InProgressState extends StatelessWidget {
alignment: Alignment.topRight,
child: _IconButton(
icon: StreamSvgIcon.close(
color: StreamChatTheme.of(context).colorTheme.white,
color: StreamChatTheme.of(context).colorTheme.barsBg,
),
onPressed: () => channel.cancelAttachmentUpload(attachmentId),
),
@@ -209,7 +209,7 @@ class _FailedState extends StatelessWidget {
children: [
_IconButton(
icon: StreamSvgIcon.retry(
color: theme.colorTheme.white,
color: theme.colorTheme.barsBg,
),
onPressed: () {
channel.retryAttachmentUpload(messageId, attachmentId);
@@ -229,7 +229,7 @@ class _FailedState extends StatelessWidget {
child: Text(
context.translations.uploadErrorLabel,
style: theme.textTheme.footnote.copyWith(
color: theme.colorTheme.white,
color: theme.colorTheme.barsBg,
),
),
),
@@ -248,7 +248,7 @@ class _SuccessState extends StatelessWidget {
backgroundColor: StreamChatTheme.of(context).colorTheme.overlayDark,
maxRadius: 12,
child: StreamSvgIcon.check(
color: StreamChatTheme.of(context).colorTheme.white,
color: StreamChatTheme.of(context).colorTheme.barsBg,
),
),
);
@@ -75,12 +75,14 @@ class AttachmentError extends StatelessWidget {
child: Container(
width: size?.width,
height: size?.height,
color:
StreamChatTheme.of(context).colorTheme.accentRed.withOpacity(.1),
color: StreamChatTheme.of(context)
.colorTheme
.accentError
.withOpacity(.1),
child: Center(
child: Icon(
Icons.error_outline,
color: StreamChatTheme.of(context).colorTheme.black,
color: StreamChatTheme.of(context).colorTheme.textHighEmphasis,
),
),
),
@@ -54,10 +54,10 @@ class FileAttachment extends AttachmentWidget {
width: size?.width ?? 100,
height: 56,
decoration: BoxDecoration(
color: colorTheme.white,
color: colorTheme.barsBg,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: colorTheme.greyWhisper,
color: colorTheme.borders,
),
),
child: Row(
@@ -141,8 +141,8 @@ class FileAttachment extends AttachmentWidget {
final colorTheme = StreamChatTheme.of(context).colorTheme;
return Shimmer.fromColors(
baseColor: colorTheme.greyGainsboro,
highlightColor: colorTheme.whiteSmoke,
baseColor: colorTheme.disabled,
highlightColor: colorTheme.inputBg,
child: image,
);
},
@@ -217,7 +217,7 @@ class FileAttachment extends AttachmentWidget {
preparing: () => Padding(
padding: const EdgeInsets.all(8),
child: _buildButton(
icon: StreamSvgIcon.close(color: theme.colorTheme.white),
icon: StreamSvgIcon.close(color: theme.colorTheme.barsBg),
fillColor: theme.colorTheme.overlayDark,
onPressed: () => channel.cancelAttachmentUpload(attachmentId),
),
@@ -225,7 +225,7 @@ class FileAttachment extends AttachmentWidget {
inProgress: (_, __) => Padding(
padding: const EdgeInsets.all(8),
child: _buildButton(
icon: StreamSvgIcon.close(color: theme.colorTheme.white),
icon: StreamSvgIcon.close(color: theme.colorTheme.barsBg),
fillColor: theme.colorTheme.overlayDark,
onPressed: () => channel.cancelAttachmentUpload(attachmentId),
),
@@ -233,15 +233,15 @@ class FileAttachment extends AttachmentWidget {
success: () => Padding(
padding: const EdgeInsets.all(8),
child: CircleAvatar(
backgroundColor: theme.colorTheme.accentBlue,
backgroundColor: theme.colorTheme.accentPrimary,
maxRadius: 12,
child: StreamSvgIcon.check(color: theme.colorTheme.white),
child: StreamSvgIcon.check(color: theme.colorTheme.barsBg),
),
),
failed: (_) => Padding(
padding: const EdgeInsets.all(8),
child: _buildButton(
icon: StreamSvgIcon.retry(color: theme.colorTheme.white),
icon: StreamSvgIcon.retry(color: theme.colorTheme.barsBg),
fillColor: theme.colorTheme.overlayDark,
onPressed: () => channel.retryAttachmentUpload(
message.id,
@@ -253,7 +253,8 @@ class FileAttachment extends AttachmentWidget {
if (message.status == MessageSendingStatus.sent) {
trailingWidget = IconButton(
icon: StreamSvgIcon.cloudDownload(color: theme.colorTheme.black),
icon: StreamSvgIcon.cloudDownload(
color: theme.colorTheme.textHighEmphasis),
visualDensity: VisualDensity.compact,
splashRadius: 16,
onPressed: () {
@@ -272,7 +273,7 @@ class FileAttachment extends AttachmentWidget {
final theme = StreamChatTheme.of(context);
final size = attachment.file?.size ?? attachment.extraData['file_size'];
final textStyle = theme.textTheme.footnote.copyWith(
color: theme.colorTheme.grey,
color: theme.colorTheme.textLowEmphasis,
);
return attachment.uploadState.when(
preparing: () => Text(fileSize(size), style: textStyle),
@@ -282,7 +283,7 @@ class FileAttachment extends AttachmentWidget {
showBackground: false,
padding: EdgeInsets.zero,
textStyle: textStyle,
progressIndicatorColor: theme.colorTheme.accentBlue,
progressIndicatorColor: theme.colorTheme.accentPrimary,
),
success: () => Text(fileSize(size), style: textStyle),
failed: (_) => Text(
@@ -52,7 +52,7 @@ class GiphyAttachment extends AttachmentWidget {
mainAxisSize: MainAxisSize.min,
children: [
Card(
color: StreamChatTheme.of(context).colorTheme.white,
color: StreamChatTheme.of(context).colorTheme.barsBg,
elevation: 2,
clipBehavior: Clip.hardEdge,
shape: const RoundedRectangleBorder(
@@ -84,7 +84,7 @@ class GiphyAttachment extends AttachmentWidget {
style: TextStyle(
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(0.5),
),
overflow: TextOverflow.ellipsis,
@@ -118,7 +118,7 @@ class GiphyAttachment extends AttachmentWidget {
Container(
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(0.2),
width: double.infinity,
height: 0.5,
@@ -142,7 +142,7 @@ class GiphyAttachment extends AttachmentWidget {
.copyWith(
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(0.5),
),
),
@@ -153,7 +153,7 @@ class GiphyAttachment extends AttachmentWidget {
width: 0.5,
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(0.2),
height: 50,
),
@@ -174,7 +174,7 @@ class GiphyAttachment extends AttachmentWidget {
.copyWith(
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(0.5),
),
maxLines: 1,
@@ -186,7 +186,7 @@ class GiphyAttachment extends AttachmentWidget {
width: 0.5,
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(0.2),
height: 50,
),
@@ -204,7 +204,7 @@ class GiphyAttachment extends AttachmentWidget {
style: TextStyle(
color: StreamChatTheme.of(context)
.colorTheme
.accentBlue,
.accentPrimary,
fontWeight: FontWeight.bold,
),
),
@@ -227,7 +227,7 @@ class GiphyAttachment extends AttachmentWidget {
StreamSvgIcon.eye(
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(0.5),
size: 16,
),
@@ -242,7 +242,7 @@ class GiphyAttachment extends AttachmentWidget {
.copyWith(
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(0.5)),
),
],
@@ -307,8 +307,8 @@ class GiphyAttachment extends AttachmentWidget {
final colorTheme = StreamChatTheme.of(context).colorTheme;
return Shimmer.fromColors(
baseColor: colorTheme.greyGainsboro,
highlightColor: colorTheme.whiteSmoke,
baseColor: colorTheme.disabled,
highlightColor: colorTheme.inputBg,
child: image,
);
},
@@ -323,7 +323,7 @@ class GiphyAttachment extends AttachmentWidget {
child: Material(
color: StreamChatTheme.of(context)
.colorTheme
.black
.textHighEmphasis
.withOpacity(.5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
@@ -336,13 +336,14 @@ class GiphyAttachment extends AttachmentWidget {
child: Row(
children: [
StreamSvgIcon.lightning(
color: StreamChatTheme.of(context).colorTheme.white,
color: StreamChatTheme.of(context).colorTheme.barsBg,
size: 16,
),
Text(
context.translations.giphyLabel.toUpperCase(),
style: TextStyle(
color: StreamChatTheme.of(context).colorTheme.white,
color:
StreamChatTheme.of(context).colorTheme.barsBg,
fontWeight: FontWeight.bold,
fontSize: 11,
),
@@ -103,8 +103,8 @@ class ImageAttachment extends AttachmentWidget {
);
final colorTheme = StreamChatTheme.of(context).colorTheme;
return Shimmer.fromColors(
baseColor: colorTheme.greyGainsboro,
highlightColor: colorTheme.whiteSmoke,
baseColor: colorTheme.disabled,
highlightColor: colorTheme.inputBg,
child: image,
);
},
@@ -72,7 +72,7 @@ class AttachmentActionsModal extends StatelessWidget {
context.translations.replyLabel,
StreamSvgIcon.iconCurveLineLeftUp(
size: 24,
color: theme.colorTheme.grey,
color: theme.colorTheme.textLowEmphasis,
),
() {
Navigator.pop(context, ReturnActionType.reply);
@@ -83,7 +83,7 @@ class AttachmentActionsModal extends StatelessWidget {
context.translations.showInChatLabel,
StreamSvgIcon.eye(
size: 24,
color: theme.colorTheme.black,
color: theme.colorTheme.textHighEmphasis,
),
onShowMessage,
),
@@ -94,7 +94,7 @@ class AttachmentActionsModal extends StatelessWidget {
: context.translations.saveImageLabel,
StreamSvgIcon.iconSave(
size: 24,
color: theme.colorTheme.grey,
color: theme.colorTheme.textLowEmphasis,
),
() {
final attachment = message.attachments[currentIndex];
@@ -145,7 +145,7 @@ class AttachmentActionsModal extends StatelessWidget {
context.translations.deleteLabel,
StreamSvgIcon.delete(
size: 24,
color: theme.colorTheme.accentRed,
color: theme.colorTheme.accentError,
),
() {
final channel = StreamChannel.of(context).channel;
@@ -166,7 +166,7 @@ class AttachmentActionsModal extends StatelessWidget {
..maybePop();
}
},
color: theme.colorTheme.accentRed,
color: theme.colorTheme.accentError,
),
]
.map<Widget>((e) => Align(
@@ -176,7 +176,7 @@ class AttachmentActionsModal extends StatelessWidget {
.insertBetween(
Container(
height: 1,
color: theme.colorTheme.greyWhisper,
color: theme.colorTheme.borders,
),
),
),
@@ -197,7 +197,7 @@ class AttachmentActionsModal extends StatelessWidget {
}) =>
Material(
key: key,
color: StreamChatTheme.of(context).colorTheme.white,
color: StreamChatTheme.of(context).colorTheme.barsBg,
child: InkWell(
onTap: onTap,
child: Padding(
@@ -242,7 +242,7 @@ class AttachmentActionsModal extends StatelessWidget {
width: 182,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: theme.colorTheme.white,
color: theme.colorTheme.barsBg,
),
child: Center(
child: progress == null
@@ -250,7 +250,7 @@ class AttachmentActionsModal extends StatelessWidget {
height: 100,
width: 100,
child: StreamSvgIcon.error(
color: theme.colorTheme.greyGainsboro,
color: theme.colorTheme.disabled,
),
)
: progress.toProgressIndicatorValue == 1.0
@@ -259,7 +259,7 @@ class AttachmentActionsModal extends StatelessWidget {
height: 160,
width: 160,
child: StreamSvgIcon.check(
color: theme.colorTheme.greyGainsboro,
color: theme.colorTheme.disabled,
),
)
: SizedBox(
@@ -272,14 +272,14 @@ class AttachmentActionsModal extends StatelessWidget {
value: progress.toProgressIndicatorValue,
strokeWidth: 8,
valueColor: AlwaysStoppedAnimation(
theme.colorTheme.accentBlue,
theme.colorTheme.accentPrimary,
),
),
Center(
child: Text(
'${progress.toPercentage}%',
style: theme.textTheme.headline.copyWith(
color: theme.colorTheme.grey,
color: theme.colorTheme.textLowEmphasis,
),
),
),
@@ -44,7 +44,7 @@ class StreamBackButton extends StatelessWidget {
padding: const EdgeInsets.all(14),
child: StreamSvgIcon.left(
size: 24,
color: StreamChatTheme.of(context).colorTheme.black,
color: StreamChatTheme.of(context).colorTheme.textHighEmphasis,
),
),
if (showUnreads)
@@ -0,0 +1,202 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:stream_chat_flutter/src/group_avatar.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart';
/// ![screenshot](https://raw.githubusercontent.com/GetStream/stream-chat-flutter/master/screenshots/channel_image.png)
/// ![screenshot](https://raw.githubusercontent.com/GetStream/stream-chat-flutter/master/screenshots/channel_image_paint.png)
///
/// It shows the current [Channel] image.
///
/// ```dart
/// class MyApp extends StatelessWidget {
/// final StreamChatClient client;
/// final Channel channel;
///
/// MyApp(this.client, this.channel);
///
/// @override
/// Widget build(BuildContext context) {
/// return MaterialApp(
/// debugShowCheckedModeBanner: false,
/// home: StreamChat(
/// client: client,
/// child: StreamChannel(
/// channel: channel,
/// child: Center(
/// child: ChannelImage(
/// channel: channel,
/// ),
/// ),
/// ),
/// ),
/// );
/// }
/// }
/// ```
///
/// The widget uses a [StreamBuilder] to render the channel information
/// image as soon as it updates.
///
/// By default the widget radius size is 40x40 pixels.
/// Set the property [constraints] to set a custom dimension.
///
/// The widget renders the ui based on the first ancestor of type
/// [StreamChatTheme].
/// Modify it to change the widget appearance.
class ChannelAvatar extends StatelessWidget {
/// Instantiate a new ChannelImage
const ChannelAvatar({
Key? key,
this.channel,
this.constraints,
this.onTap,
this.borderRadius,
this.selected = false,
this.selectionColor,
this.selectionThickness = 4,
}) : super(key: key);
/// [BorderRadius] to display the widget
final BorderRadius? borderRadius;
/// The channel to show the image of
final Channel? channel;
/// The diameter of the image
final BoxConstraints? constraints;
/// The function called when the image is tapped
final VoidCallback? onTap;
/// If image is selected
final bool selected;
/// Selection color for image
final Color? selectionColor;
/// Thickness of selection image
final double selectionThickness;
@override
Widget build(BuildContext context) {
final streamChat = StreamChat.of(context);
final channel = this.channel ?? StreamChannel.of(context).channel;
assert(channel.state != null, 'Channel ${channel.id} is not initialized');
final chatThemeData = StreamChatTheme.of(context);
final colorTheme = chatThemeData.colorTheme;
final previewTheme = chatThemeData.channelPreviewTheme.avatarTheme;
return BetterStreamBuilder<Map<String, dynamic>>(
stream: channel.extraDataStream,
initialData: channel.extraData,
builder: (context, extraData) {
final channelImage = extraData['image'];
if (channelImage != null) {
Widget child = ClipRRect(
borderRadius: borderRadius ?? previewTheme?.borderRadius,
child: Container(
constraints: constraints ?? previewTheme?.constraints,
decoration: BoxDecoration(color: colorTheme.accentPrimary),
child: InkWell(
onTap: onTap,
child: CachedNetworkImage(
imageUrl: channelImage,
errorWidget: (_, __, ___) => Center(
child: Text(
extraData['name']?[0] ?? '',
style: TextStyle(
color: colorTheme.barsBg,
fontWeight: FontWeight.bold,
),
),
),
fit: BoxFit.cover,
),
),
),
);
if (selected) {
child = ClipRRect(
key: const Key('selectedImage'),
borderRadius: BorderRadius.circular(selectionThickness) +
(borderRadius ??
previewTheme?.borderRadius ??
BorderRadius.zero),
child: Container(
constraints: constraints ?? previewTheme?.constraints,
color: selectionColor ?? colorTheme.accentPrimary,
child: Padding(
padding: EdgeInsets.all(selectionThickness),
child: child,
),
),
);
}
return child;
}
final currentUser = streamChat.user!;
final otherMembers = channel.state!.members
.where((it) => it.userId != currentUser.id)
.toList(growable: false);
// our own space, no other members
if (otherMembers.isEmpty) {
return BetterStreamBuilder<User>(
stream: streamChat.client.state.userStream.map((it) => it!),
initialData: currentUser,
builder: (context, user) => UserAvatar(
borderRadius: borderRadius ?? previewTheme?.borderRadius,
user: user,
constraints: constraints ?? previewTheme?.constraints,
onTap: onTap != null ? (_) => onTap!() : null,
selected: selected,
selectionColor: selectionColor ?? colorTheme.accentPrimary,
selectionThickness: selectionThickness,
),
);
}
// 1-1 Conversation
if (otherMembers.length == 1) {
final member = otherMembers.first;
return BetterStreamBuilder<Member>(
stream: channel.state!.membersStream.map(
(members) => members.firstWhere(
(it) => it.userId == member.userId,
orElse: () => member,
),
),
initialData: member,
builder: (context, member) => UserAvatar(
borderRadius: borderRadius ?? previewTheme?.borderRadius,
user: member.user!,
constraints: constraints ?? previewTheme?.constraints,
onTap: onTap != null ? (_) => onTap!() : null,
selected: selected,
selectionColor: selectionColor ?? colorTheme.accentPrimary,
selectionThickness: selectionThickness,
),
);
}
// Group conversation
return GroupAvatar(
members: otherMembers,
borderRadius: borderRadius ?? previewTheme?.borderRadius,
constraints: constraints ?? previewTheme?.constraints,
onTap: onTap,
selected: selected,
selectionColor: selectionColor ?? colorTheme.accentPrimary,
selectionThickness: selectionThickness,
);
},
);
}
}
@@ -33,7 +33,7 @@ class _ChannelBottomSheetState extends State<ChannelBottomSheet> {
final isOwner = userAsMember.role == 'owner';
return Material(
color: _streamChatThemeData.colorTheme.white,
color: _streamChatThemeData.colorTheme.barsBg,
clipBehavior: Clip.antiAlias,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
@@ -147,7 +147,7 @@ class _ChannelBottomSheetState extends State<ChannelBottomSheet> {
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: StreamSvgIcon.user(
color: _streamChatThemeData.colorTheme.grey,
color: _streamChatThemeData.colorTheme.textLowEmphasis,
),
),
title: context.translations.viewInfoLabel,
@@ -158,7 +158,7 @@ class _ChannelBottomSheetState extends State<ChannelBottomSheet> {
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: StreamSvgIcon.userRemove(
color: _streamChatThemeData.colorTheme.grey,
color: _streamChatThemeData.colorTheme.textLowEmphasis,
),
),
title: context.translations.leaveGroupLabel,
@@ -177,11 +177,11 @@ class _ChannelBottomSheetState extends State<ChannelBottomSheet> {
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: StreamSvgIcon.delete(
color: _streamChatThemeData.colorTheme.accentRed,
color: _streamChatThemeData.colorTheme.accentError,
),
),
title: context.translations.deleteConversationLabel,
titleColor: _streamChatThemeData.colorTheme.accentRed,
titleColor: _streamChatThemeData.colorTheme.accentError,
onTap: () async {
setState(() {
_showActions = false;
@@ -196,7 +196,7 @@ class _ChannelBottomSheetState extends State<ChannelBottomSheet> {
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: StreamSvgIcon.closeSmall(
color: _streamChatThemeData.colorTheme.grey,
color: _streamChatThemeData.colorTheme.textLowEmphasis,
),
),
title: context.translations.cancelLabel,
@@ -225,7 +225,7 @@ class _ChannelBottomSheetState extends State<ChannelBottomSheet> {
question: context.translations.deleteConversationQuestion,
cancelText: context.translations.cancelLabel,
icon: StreamSvgIcon.delete(
color: _streamChatThemeData.colorTheme.accentRed,
color: _streamChatThemeData.colorTheme.accentError,
),
);
final channel = _streamChannelState.channel;
@@ -243,7 +243,7 @@ class _ChannelBottomSheetState extends State<ChannelBottomSheet> {
question: context.translations.leaveConversationQuestion,
cancelText: context.translations.cancelLabel,
icon: StreamSvgIcon.userRemove(
color: _streamChatThemeData.colorTheme.accentRed,
color: _streamChatThemeData.colorTheme.accentError,
),
);
if (res == true) {

Some files were not shown because too many files have changed in this diff Show More