Merge pull request #238 from GetStream/nash/core-sample-app

Add example to core package
This commit is contained in:
Salvatore Giordano
2021-01-28 10:34:17 +01:00
committed by GitHub
8 changed files with 271 additions and 123 deletions
+1
View File
@@ -1,6 +1,7 @@
.DS_Store
.atom/
.idea/
.vscode/
.packages
.pub/
@@ -1,3 +1,4 @@
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
+1 -1
View File
@@ -156,7 +156,7 @@ class _MessageViewState extends State<MessageView> {
/// Convenience method for scrolling the list view when a new message is sent.
void _updateList() {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
@@ -1,3 +1,4 @@
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
@@ -1,121 +1,296 @@
import 'package:flutter/material.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart';
void main() {
runApp(MyApp());
Future<void> main() async {
/// Create a new instance of [Client] passing the apikey obtained from your
/// project dashboard.
final client = Client('b67pax5b2wdq');
/// Set the current user. 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.setUser(
User(
id: 'cool-shadow-7',
extraData: {
'image':
'https://getstream.io/random_png/?id=cool-shadow-7&amp;name=Cool+shadow',
},
),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY29vbC1zaGFkb3ctNyJ9.gkOlCRb1qgy4joHPaxFwPOdXcGvSPvp6QY0S4mpRkVo',
);
runApp(
StreamExample(
client: client,
),
);
}
// ignore: public_member_api_docs
class MyApp extends StatelessWidget {
// This widget is the root of your application.
/// Example application using Stream Chat core widgets.
/// Stream Chat Core is a set of Flutter wrappers which provide basic functionality
/// for building Flutter applications using Stream.
/// If you'd prefer using pre-made UI widgets for your app, please see our other
/// package, `stream_chat_flutter`.
class StreamExample extends StatelessWidget {
/// Minimal example using Stream's core Flutter package.
/// If you'd prefer using pre-made UI widgets for your app, please see our other
/// package, `stream_chat_flutter`.
const StreamExample({
Key key,
@required this.client,
}) : super(key: key);
/// Instance of Stream Client.
/// Stream's [Client] 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 Client client;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
title: 'Stream Chat Core Example',
home: HomeScreen(),
builder: (context, child) => StreamChatCore(
client: client,
child: child,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
// ignore: public_member_api_docs
class MyHomePage extends StatefulWidget {
// ignore: public_member_api_docs
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
// ignore: public_member_api_docs
final String title;
/// Basic layout displaying a list of [Channel]s the user is a part of.
/// This is implemented using [ChannelListCore].
///
/// [ChannelListCore] is a `builder` with callbacks for constructing UIs based
/// on different scenarios.
class HomeScreen extends StatelessWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Channels'),
),
body: ChannelsBloc(
child: ChannelListCore(
emptyBuilder: (BuildContext context) {
return Center(
child: Text('Looks like you are not in any channels'),
);
},
loadingBuilder: (BuildContext context) {
return Center(
child: SizedBox(
height: 100.0,
width: 100.0,
child: CircularProgressIndicator(),
),
);
},
errorBuilder: (Error error) {
return Center(
child: Text(
'Oh no, something went wrong. Please check your config.'),
);
},
listBuilder: (
BuildContext context,
List<Channel> channels,
) =>
ListView.builder(
itemCount: channels.length,
itemBuilder: (BuildContext context, int index) {
final _item = channels[index];
return ListTile(
title: Text(_item.name),
subtitle: Text(_item.state.lastMessage.text),
onTap: () {
/// Display a list of messages when the user taps on an item.
/// We can use [StreamChannel] to wrap our [MessageScreen] screen
/// with the selected channel.
///
/// This allows us to use a built-in inherited widget for accessing
/// our `channel` later on.
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => StreamChannel(
channel: _item,
child: MessageScreen(),
),
),
);
},
);
},
),
),
),
);
}
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
/// A list of messages sent in the current channel.
/// When a user taps on a channel in [HomeScreen], a navigator push [MessageScreen]
/// to display the list of messages in the selected channel.
///
/// This is implemented using [MessageListCore], a convenience builder with
/// callbacks for building UIs based on different api results.
class MessageScreen extends StatefulWidget {
@override
_MessageScreenState createState() => _MessageScreenState();
}
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
class _MessageScreenState extends State<MessageScreen> {
TextEditingController _controller;
ScrollController _scrollController;
@override
void initState() {
super.initState();
_controller = TextEditingController();
_scrollController = ScrollController();
}
@override
void dispose() {
_controller.dispose();
_scrollController.dispose();
super.dispose();
}
void _updateList() {
_scrollController.animateTo(
0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
/// To access the current channel, we can use the `.of()` method on [StreamChannel]
/// to fetch the closest instance.
final channel = StreamChannel.of(context).channel;
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
title: Text(channel.name),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
body: SafeArea(
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
children: [
Expanded(
child: MessageListCore(
emptyBuilder: (BuildContext context) {
return Center(
child: Text('Nothing here yet'),
);
},
loadingBuilder: (BuildContext context) {
return Center(
child: SizedBox(
height: 100.0,
width: 100.0,
child: CircularProgressIndicator(),
),
);
},
messageListBuilder: (
BuildContext context,
List<Message> messages,
) {
return ListView.builder(
controller: _scrollController,
itemCount: messages.length,
reverse: true,
itemBuilder: (BuildContext context, int index) {
final item = messages[index];
final client = StreamChatCore.of(context).client;
if (item.user.id == client.uid) {
return Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(item.text),
),
);
} else {
return Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(item.text),
),
);
}
},
);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
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 {
if (_controller.value.text.isNotEmpty) {
await 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,
),
),
),
),
)
],
),
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
/// Extensions can be used to add functionality to the SDK. In the examples
/// below, we add two simple extensions to the [Client] and [Channel].
extension on Client {
/// Fetches the current user id.
String get uid => state.user.id;
}
extension on Channel {
/// Fetches the name of the channel by accessing [extraData] or [cid].
String get name {
final _channelName = extraData['name'];
if (_channelName != null) {
return _channelName;
} else {
return cid;
}
}
}
@@ -1,30 +0,0 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:example/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}