feet/lib/main.dart
2022-12-30 00:27:35 +01:00

118 lines
3.1 KiB
Dart

import 'dart:async';
import 'package:feet/widgets/homepage_post.dart';
import 'package:feet/widgets/login_prompt.dart';
import 'package:flutter/material.dart';
import 'package:dynamic_color/dynamic_color.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'api/api.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final api = FeverAPI();
SharedPreferences? prefs;
MyApp({super.key});
Future<bool> _loadPrefs() async {
var prefs = await SharedPreferences.getInstance();
this.prefs = prefs;
var apiKey = prefs.getString('apiKey'),
apiUrl = prefs.getString('apiUrl');
if (apiUrl != null && apiKey != null) {
api.apiUrl = apiUrl;
api.apiKey = apiKey;
return true;
}
return false;
}
@override
Widget build(BuildContext context) {
return DynamicColorBuilder(
builder: ((lightDynamic, darkDynamic) => MaterialApp(
title: 'Feet',
theme: ThemeData(
brightness: Brightness.light,
useMaterial3: true,
colorScheme: lightDynamic,
),
darkTheme: ThemeData(
brightness: Brightness.dark,
useMaterial3: true,
colorScheme: darkDynamic,
),
themeMode: ThemeMode.system,
home: FutureBuilder<bool>(
builder: (context, snapshot) {
if (snapshot.hasData && prefs != null) return MyHomePage(title: 'Feet', api: api, prefs: prefs!);
return const SizedBox();
},
future: _loadPrefs(),
),
)),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
final FeverAPI api;
final SharedPreferences prefs;
const MyHomePage({ super.key, required this.title, required this.api, required this.prefs });
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
var loggedIn = widget.api.loggedIn();
// I'm aware that this is stupid, but I'm sick and tired and really don't care as long as it works
if (!loggedIn) {
Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() {
loggedIn = widget.api.loggedIn();
});
if (loggedIn) timer.cancel();
});
}
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: [
IconButton(
onPressed: () {
widget.api.request()
.withFeeds()
.withGroups()
.withItems()
.execute()
.then((_) { setState(() {}); });
},
icon: const Icon(Icons.replay_outlined),
),
],
),
body: loggedIn
? ListView(
children: widget.api.cache.items.getAll()
.values
.map((value) => HomepagePost(post: value))
.toList()
..sort((a, b) => b.post.createdOnTime.millisecondsSinceEpoch.compareTo(a.post.createdOnTime.millisecondsSinceEpoch)),
)
: Center(child: LoginPrompt(api: widget.api)),
);
}
}