Add stubbed out UI for experimentation

This commit is contained in:
Hank Grabowski 2022-11-08 20:28:48 -06:00
parent a9db15887d
commit 5d9986121f
5 changed files with 310 additions and 96 deletions

View file

@ -1,115 +1,63 @@
import 'package:flutter/material.dart';
import 'package:flutter_portal/globals.dart';
import 'package:flutter_portal/routes.dart';
import 'package:flutter_portal/screens/sign_in.dart';
import 'package:flutter_portal/services/auth_service.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
getIt.registerLazySingleton<AuthService>(() => AuthService());
runApp(const App());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
class App extends StatelessWidget {
const App({super.key});
// This widget is the root of your application.
@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,
// 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,
// ),
// home: const Home(),
// );
return MultiProvider(
providers: [
ChangeNotifierProvider<AuthService>(
create: (_) => getIt<AuthService>(),
lazy: true,
)
],
child: MaterialApp.router(
theme: ThemeData(
primarySwatch: Colors.indigo,
),
debugShowCheckedModeBanner: false,
routerDelegate: appRouter.routerDelegate,
routeInformationProvider: appRouter.routeInformationProvider,
routeInformationParser: appRouter.routeInformationParser,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// 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".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
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 Home extends StatelessWidget {
const Home({super.key});
@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.
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),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
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>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
return SignInScreen();
}
}

29
lib/routes.dart Normal file
View file

@ -0,0 +1,29 @@
import 'package:go_router/go_router.dart';
import 'screens/home.dart';
import 'screens/sign_in.dart';
class ScreenPaths {
static String splash = '/splash';
static String home = '/';
static String signin = '/signin';
static String signup = '/signup';
static String settings = '/settings';
}
bool needAuthChangeInitialized = true;
final appRouter = GoRouter(
initialLocation: ScreenPaths.signin,
debugLogDiagnostics: true,
routes: [
GoRoute(
path: ScreenPaths.signin,
name: ScreenPaths.signin,
builder: (context, state) => SignInScreen(),
),
GoRoute(
path: ScreenPaths.home,
name: ScreenPaths.home,
builder: (context, state) => HomeScreen(),
),
]);

124
lib/screens/home.dart Normal file
View file

@ -0,0 +1,124 @@
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:result_monad/result_monad.dart';
import '../controls/padding.dart';
import '../friendica_client.dart';
import '../globals.dart';
import '../models/exec_error.dart';
import '../models/timeline_entry.dart';
import '../services/auth_service.dart';
class HomeScreen extends StatelessWidget {
final postText = TextEditingController();
@override
Widget build(BuildContext context) {
final clientResult = getIt<AuthService>().currentClient;
final body = clientResult.fold(onSuccess: (client) {
return Column(
children: [
TextFormField(
controller: postText,
maxLines: 4,
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).backgroundColor,
),
borderRadius: BorderRadius.circular(5.0),
),
),
),
const VerticalPadding(),
ElevatedButton(onPressed: null, child: const Text('Post')),
const VerticalPadding(),
Expanded(child: buildTimelineComponent(context, client))
],
);
}, onError: (error) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Error getting client: $error '),
],
),
);
});
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: body,
);
}
Widget buildTimelineComponent(BuildContext context, FriendicaClient client) {
return FutureBuilder<Result<List<TimelineEntry>, ExecError>>(
future: client.getHomeTimeline(page: 1, count: 50),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return Text('Loading');
}
if (snapshot.hasError) {
return Text('Got an error: ${snapshot.error}');
}
if (snapshot.data == null) {
return Text('Got null data');
}
final result = snapshot.data!;
if (result.isFailure) {
return Text('Got an error: ${result.error}');
}
final items = result.value;
return ListView.separated(
itemBuilder: (context, index) {
final item = items[index];
return ListTile(
subtitle: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
HtmlWidget(
item.body,
onTapUrl: (url) async {
print(url);
return true;
},
onTapImage: (imageMetadata) {
print(imageMetadata);
},
),
if (item.links.isNotEmpty)
Text('Preview: ${item.links.first.url}'),
if (item.mediaAttachments.isNotEmpty)
...item.mediaAttachments
.map((a) => Text('Media: ${a.uri}')),
Text(
'Engagement -- Likes: ${item.likes.length}, Dislikes: ${item.dislikes.length}, ')
],
),
),
//trailing: Text(item.parentId),
title: Text(
'${item.id} for ${item.author} for post ${item.parentId}'),
trailing: Text(DateTime.fromMillisecondsSinceEpoch(
item.creationTimestamp * 1000)
.toIso8601String()),
);
},
separatorBuilder: (context, index) => Divider(),
itemCount: items.length,
);
});
}
}

100
lib/screens/sign_in.dart Normal file
View file

@ -0,0 +1,100 @@
import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:result_monad/result_monad.dart';
import '../controls/padding.dart';
import '../friendica_client.dart';
import '../globals.dart';
import '../models/credentials.dart';
import '../routes.dart';
import '../services/auth_service.dart';
import '../utils/snackbar_builder.dart';
class SignInScreen extends StatelessWidget {
final formKey = GlobalKey<FormState>();
final usernameController = TextEditingController();
final passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sign In'),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
key: formKey,
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
controller: usernameController,
validator: (value) => EmailValidator.validate(value ?? '')
? null
: 'Not a valid Friendica Account Address',
decoration: InputDecoration(
prefixIcon: Icon(Icons.alternate_email),
hintText: 'Username (user@example.com)',
border: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).backgroundColor,
),
borderRadius: BorderRadius.circular(5.0),
),
labelText: 'Username',
),
),
const VerticalPadding(),
TextFormField(
obscureText: true,
controller: passwordController,
decoration: InputDecoration(
prefixIcon: Icon(Icons.password),
hintText: 'Password',
border: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).backgroundColor,
),
borderRadius: BorderRadius.circular(5.0),
),
labelText: 'Password',
),
),
const VerticalPadding(),
ElevatedButton(
onPressed: () => _signIn(context),
child: Text('Signin'),
),
],
),
),
),
),
);
}
void _signIn(BuildContext context) async {
if (formKey.currentState?.validate() ?? false) {
print('Attempting login...');
await Credentials.buildFromHandle(
usernameController.text,
passwordController.text,
)
.andThenSuccess((creds) => FriendicaClient(credentials: creds))
.andThenAsync((client) async =>
(await client.getMyProfile()).mapValue((_) => client))
.match(onSuccess: (client) {
print('Logged in');
getIt<AuthService>().updateClient(client);
context.pushNamed(ScreenPaths.home);
}, onError: (error) {
buildSnackbar(context, 'Error logging in: $error');
});
}
}
}

View file

@ -0,0 +1,13 @@
import 'package:flutter/material.dart';
Future<void> buildSnackbar(BuildContext context, String message,
{int durationSec = 3}) async {
final snackBar = SnackBar(
content: SelectableText(message),
duration: Duration(seconds: durationSec),
action: SnackBarAction(
label: 'Dismiss',
onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(),
));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}