repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/utilities/background.dart | import 'package:flutter/material.dart';
class BackgroundBody extends StatelessWidget {
var theme;
var child;
BackgroundBody({required this.theme, required this.child});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
height: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
image: theme.getTheme().brightness == Brightness.light
? const AssetImage('images/lightBackground.png')
: const AssetImage('images/darkBackground.png'),
fit: BoxFit.cover,
opacity: 0.3,
),
),
child: child,
);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/utilities/const.dart | import 'package:flutter/material.dart';
const kMainFontFamily = 'AbrilFatface';
const kCardColor = Colors.white24;
const kRepoURL = 'https://github.com/shamilkeheliya/NASA-MobileApp';
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/themeData/theme_manager.dart | import 'package:flutter/material.dart';
import 'package:nasa_mobileapp/themeData/storage_manager.dart';
class ThemeNotifier with ChangeNotifier {
final darkTheme = ThemeData(
primarySwatch: Colors.grey,
//primaryColor: const Color(0xFF0B3D91),
primaryColor: const Color(0xFF021f4f),
brightness: Brightness.dark,
backgroundColor: const Color(0xFF212121),
accentColor: Colors.white,
accentIconTheme: const IconThemeData(color: Colors.black),
dividerColor: Colors.black12,
canvasColor: Colors.white,
cardColor: const Color(0x77021f6f),
);
final lightTheme = ThemeData(
primarySwatch: Colors.grey,
primaryColor: Colors.white,
brightness: Brightness.light,
backgroundColor: const Color(0xFFE5E5E5),
accentColor: Colors.black,
accentIconTheme: const IconThemeData(color: Colors.white),
dividerColor: Colors.white54,
//canvasColor: const Color(0xFF021f4f),
canvasColor: const Color(0xFF0B3D91),
cardColor: Colors.white,
);
ThemeData _themeData = ThemeData(
primaryColor: const Color(0xFF021f4f),
);
ThemeData getTheme() => _themeData;
ThemeNotifier() {
StorageManager.readData('themeMode').then((value) {
//print('value read from storage: ' + value.toString());
var themeMode = value ?? 'dark';
if (themeMode == 'light') {
_themeData = lightTheme;
} else {
//print('setting dark theme');
_themeData = darkTheme;
}
notifyListeners();
});
}
void setDarkMode() async {
_themeData = darkTheme;
StorageManager.saveData('themeMode', 'dark');
notifyListeners();
}
void setLightMode() async {
_themeData = lightTheme;
StorageManager.saveData('themeMode', 'light');
notifyListeners();
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/themeData/storage_manager.dart | import 'package:shared_preferences/shared_preferences.dart';
class StorageManager {
static void saveData(String key, dynamic value) async {
final prefs = await SharedPreferences.getInstance();
if (value is int) {
prefs.setInt(key, value);
} else if (value is String) {
prefs.setString(key, value);
} else if (value is bool) {
prefs.setBool(key, value);
} else {
print("Invalid Type");
}
}
static Future<dynamic> readData(String key) async {
final prefs = await SharedPreferences.getInstance();
dynamic obj = prefs.get(key);
return obj;
}
static Future<bool> deleteData(String key) async {
final prefs = await SharedPreferences.getInstance();
return prefs.remove(key);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/customWidgets/homePageTopIcons.dart | import 'package:flutter/material.dart';
import 'package:nasa_mobileapp/utilities/const.dart';
import 'package:url_launcher/url_launcher.dart';
class HomePageTopIconsRow extends StatelessWidget {
var theme;
HomePageTopIconsRow({
required this.theme,
});
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
onPressed: () {
theme.getTheme().brightness == Brightness.light
? theme.setDarkMode()
: theme.setLightMode();
},
icon: Icon(
Icons.brightness_4_outlined,
color: Theme.of(context).canvasColor,
),
),
IconButton(
onPressed: () async {
if (!await launchUrl(Uri.parse(kRepoURL))) {
throw 'Could not launch About App';
}
},
icon: Icon(
Icons.info_outline,
color: Theme.of(context).canvasColor,
),
),
],
);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/customWidgets/yearTestField.dart | import 'package:flutter/material.dart';
class CustomYearTextField extends StatelessWidget {
TextEditingController controller;
Function(String) onChanged;
bool visible;
Function() onPressed;
String hintText;
CustomYearTextField({
required this.hintText,
required this.controller,
required this.onChanged,
required this.visible,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return Flexible(
child: TextField(
controller: controller,
onChanged: onChanged,
maxLength: 4,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: hintText,
border: const OutlineInputBorder(),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).canvasColor,
),
),
suffixIcon: Visibility(
visible: visible,
child: IconButton(
onPressed: onPressed,
icon: Icon(
Icons.clear,
color: Theme.of(context).canvasColor,
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/customWidgets/dialogBoxButton.dart | import 'package:flutter/material.dart';
class DialogBoxArrowButton extends StatelessWidget {
late Function() onPressed;
late bool visible;
late IconData iconData;
DialogBoxArrowButton({
required this.onPressed,
required this.visible,
required this.iconData,
});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 50,
width: 50,
child: Visibility(
visible: visible,
child: MaterialButton(
onPressed: onPressed,
padding: EdgeInsets.zero,
child: SizedBox(
height: 50,
width: 50,
child: Card(
elevation: 5,
color: Theme.of(context).canvasColor,
child: Icon(
iconData,
color: Theme.of(context).primaryColor,
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/customWidgets/customFloatingActionButton.dart | import 'package:flutter/material.dart';
import 'package:nasa_mobileapp/customWidgets/changePageDialogBox.dart';
import 'package:nasa_mobileapp/views/homePage.dart';
class GoHomeFloatingActionButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FloatingActionButton(
heroTag: 'goHome',
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomePage()));
},
backgroundColor: Theme.of(context).canvasColor,
child: Icon(
Icons.home_outlined,
color: Theme.of(context).primaryColor,
),
);
}
}
class GoBackFloatingActionButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: () {
Navigator.pop(context);
},
tooltip: 'Go Back',
backgroundColor: Theme.of(context).canvasColor,
child: Icon(
Icons.close,
color: Theme.of(context).primaryColor,
),
);
}
}
class ChangePageFloatingActionButton extends StatelessWidget {
var data, pageNumber;
late Function(bool) isLoading;
ChangePageFloatingActionButton({
required this.data,
required this.pageNumber,
required this.isLoading,
});
@override
Widget build(BuildContext context) {
return data != null
? FloatingActionButton(
heroTag: 'changePage',
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return ChangePageDialogBox(
data: data,
pageNumber: pageNumber,
isLoading: isLoading,
);
});
},
backgroundColor: Theme.of(context).canvasColor,
child: Text(
'Page\n$pageNumber',
textAlign: TextAlign.center,
),
)
: const SizedBox();
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/customWidgets/changePageDialogBox.dart | import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:nasa_mobileapp/customWidgets/dialogBoxButton.dart';
import 'package:nasa_mobileapp/views/viewList.dart';
class ChangePageDialogBox extends StatefulWidget {
var data, pageNumber;
late Function(bool) isLoading;
ChangePageDialogBox({
required this.data,
required this.pageNumber,
required this.isLoading,
});
@override
_ChangePageDialogBoxState createState() => _ChangePageDialogBoxState();
}
class _ChangePageDialogBoxState extends State<ChangePageDialogBox> {
bool isVisiable = true, isPrevious = false, isNext = false;
late String previousURL, nextURL;
List list = [];
int itemsCount = 0;
@override
void initState() {
super.initState();
getData();
}
getData() {
list = widget.data;
itemsCount = list.length;
if (itemsCount == 1) {
if (list[0]['rel'] == 'next') {
setState(() {
isNext = true;
nextURL = list[0]['href'];
print(nextURL);
});
}
if (list[0]['rel'] == 'prev') {
setState(() {
isPrevious = true;
previousURL = list[0]['href'];
});
}
}
if (itemsCount == 2) {
setState(() {
isPrevious = true;
isNext = true;
if (list[0]['rel'] == 'prev') {
previousURL = list[0]['href'];
nextURL = list[1]['href'];
} else {
nextURL = list[0]['href'];
previousURL = list[1]['href'];
}
});
}
}
@override
Widget build(BuildContext context) {
return Visibility(
visible: isVisiable,
child: AlertDialog(
backgroundColor: Theme.of(context).primaryColor,
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
DialogBoxArrowButton(
onPressed: () => changePage(previousURL),
visible: isPrevious,
iconData: Icons.chevron_left,
),
Text(
'Page ${widget.pageNumber}',
style: TextStyle(
color: Theme.of(context).canvasColor,
),
),
DialogBoxArrowButton(
onPressed: () => changePage(nextURL),
visible: isNext,
iconData: Icons.chevron_right,
),
],
),
),
);
}
changePage(String url) async {
setState(() {
widget.isLoading(true);
isVisiable = false;
});
String pageNumber = getPageNumber(url);
http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
setState(() {
widget.isLoading(false);
});
var data = jsonDecode(response.body);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ViewList(
url: url,
data: data,
pageNumber: pageNumber,
),
),
);
}
}
String getPageNumber(String url) {
bool isSearching = true;
String pageNumber = '';
int idx;
while (isSearching) {
idx = url.indexOf("&");
url = url.substring(idx + 1).trim();
idx = url.indexOf("=");
if (url.substring(0, idx).trim() == 'page') {
isSearching = false;
pageNumber = url.substring(idx + 1).trim();
}
}
return pageNumber;
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/customWidgets/customElevatedButton.dart | import 'package:flutter/material.dart';
class CustomElevatedButton extends StatelessWidget {
late String text;
late Function() onPressed;
CustomElevatedButton({
required this.onPressed,
required this.text,
});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
style: ElevatedButton.styleFrom(
primary: Theme.of(context).canvasColor,
),
child: Text(
text,
style: TextStyle(
color: Theme.of(context).primaryColor,
),
),
);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib | mirrored_repositories/NASA-MobileApp/lib/customWidgets/detailsCard.dart | import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:cached_network_image/cached_network_image.dart';
class CustomDetailCard extends StatelessWidget {
late String title, description, image;
CustomDetailCard({
required this.title,
required this.description,
required this.image,
});
@override
Widget build(BuildContext context) {
return Card(
color: Theme.of(context).cardColor,
elevation: 5,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
softWrap: true,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Theme.of(context).canvasColor,
),
),
const SizedBox(height: 5),
Text(
description,
maxLines: 4,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Theme.of(context).canvasColor,
),
),
],
),
),
),
SizedBox(
height: 100,
width: 100,
child: CachedNetworkImage(
imageUrl: image,
placeholder: (context, url) => Transform.scale(
scale: 0.3,
child: const CircularProgressIndicator(),
),
errorWidget: (context, url, error) => const Icon(Icons.error),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib/customWidgets | mirrored_repositories/NASA-MobileApp/lib/customWidgets/singleContentView/imageView.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class ImageView extends StatefulWidget {
var url;
ImageView({
required this.url,
});
@override
_ImageViewState createState() => _ImageViewState();
}
class _ImageViewState extends State<ImageView> {
@override
Widget build(BuildContext context) {
return Flex(
direction: Axis.horizontal,
children: [
Expanded(
child: CachedNetworkImage(
imageUrl: widget.url,
placeholder: (context, url) => SpinKitDualRing(
color: Theme.of(context).canvasColor,
size: 50.0,
),
errorWidget: (context, url, error) => const Icon(Icons.error),
),
),
],
);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib/customWidgets | mirrored_repositories/NASA-MobileApp/lib/customWidgets/singleContentView/customSnackBar.dart | import 'package:flutter/material.dart';
SnackBar successfulSnackBar() {
return SnackBar(
content: const Text('Image Download Successful'),
action: SnackBarAction(
label: 'OK',
onPressed: () {},
),
);
}
SnackBar failedSnackBar() {
return SnackBar(
content: const Text('Downloading Failed'),
action: SnackBarAction(
label: 'OK',
onPressed: () {},
),
);
}
SnackBar noDataSnackBar() {
return SnackBar(
content: const Text('No Data to show'),
action: SnackBarAction(
label: 'OK',
onPressed: () {},
),
);
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib/customWidgets | mirrored_repositories/NASA-MobileApp/lib/customWidgets/singleContentView/showDownloading.dart | import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class ShowDownloading extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
primary: Theme.of(context).canvasColor,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'Downloading',
style: TextStyle(
//fontSize: 18,
color: Theme.of(context).primaryColor,
),
),
SpinKitThreeBounce(
color: Theme.of(context).primaryColor,
size: 10.0,
),
],
),
);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp/lib/customWidgets | mirrored_repositories/NASA-MobileApp/lib/customWidgets/singleContentView/textView.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class TextView extends StatelessWidget {
late String title, description, date_created;
Color textColor;
TextView({
required this.title,
required this.description,
required this.textColor,
required this.date_created,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10),
child: Card(
color: Theme.of(context).cardColor,
elevation: 5,
child: Padding(
padding: const EdgeInsets.all(15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
maxLines: 10,
style: TextStyle(
fontSize: 35,
fontWeight: FontWeight.bold,
color: textColor,
),
),
const SizedBox(height: 5),
Text(
description,
maxLines: 10,
style: TextStyle(
fontSize: 16,
color: textColor,
),
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
date_created,
style: TextStyle(
fontSize: 14,
color: textColor,
),
),
],
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/NASA-MobileApp | mirrored_repositories/NASA-MobileApp/test/widget_test.dart | // 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:nasa_mobileapp/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);
});
}
| 0 |
mirrored_repositories/ncovid | mirrored_repositories/ncovid/lib/main.dart | import 'package:flutter/material.dart';
import 'package:tojuwa/screens/homepage.dart';
import 'package:dynamic_theme/dynamic_theme.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return DynamicTheme(
defaultBrightness: Brightness.light,
data: (brightness) => new ThemeData(
primarySwatch: Colors.indigo,
brightness: brightness,
),
themedWidgetBuilder: (context, theme) {
return MaterialApp(
title: 'Toju wa',
debugShowCheckedModeBanner: false,
theme: theme,
home: Home(),
);
});
}
}
| 0 |
mirrored_repositories/ncovid | mirrored_repositories/ncovid/lib/apiKey.dart | String apiKey = "14404d1267a94b8fa3d50e5364ed10d4";
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/network/newsdata.dart | import 'package:http/http.dart' as http;
import 'package:tojuwa/models/article.dart';
import 'dart:convert';
import 'package:tojuwa/apiKey.dart';
class NewsForCorona {
List<Article> news = [];
Future<void> getNewsForCorona() async {
String url =
"http://newsapi.org/v2/top-headlines?country=ng&q=corona&apiKey=$apiKey";
var response = await http.get(url);
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == "ok") {
jsonData["articles"].forEach((element) {
if (element['urlToImage'] != null && element['description'] != null) {
Article article = Article(
title: element['title'],
author: element['author'],
description: element['description'],
urlToImage: element['urlToImage'],
publshedAt: DateTime.parse(element['publishedAt']),
content: element["content"],
articleUrl: element["url"],
);
news.add(article);
}
});
}
}
} | 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/network/coviddata.dart | import 'package:http/http.dart' as http;
import 'package:tojuwa/models/coviddata.dart';
import 'dart:convert';
class CasesForCorona {
List<Covid> cases = [];
Future<void> getCasesForCorona() async {
String url = "https://covid19.mathdro.id/api/countries/nigeria/confirmed"; // enter new nigeria url
var response = await http.get(url);
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == "ok") {
Covid gottencases = Covid(
confirmed: jsonData['confirmed']['value'],
recovered: jsonData['recovered']['value'],
deaths: jsonData['deaths']['value'],
);
cases.add(gottencases);
} else {
print(response.statusCode);
}
}
}
class GlobalTotalForCorona {
List<Covid> cases = [];
Future<void> getTotalCasesForCorona() async {
String url = "https://covid19.mathdro.id/api";
var response = await http.get(url);
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == "ok") {
Covid gottencases = Covid(
confirmed: jsonData['confirmed']['value'],
recovered: jsonData['recovered']['value'],
deaths: jsonData['deaths']['value'],
);
cases.add(gottencases);
} else {
print(response.statusCode);
}
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/widgets/info_box.dart | import 'package:tojuwa/utils/constants.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class InfoBox extends StatelessWidget {
final String title;
final Icon icon;
final Color color;
final int number;
final Function onPressed;
InfoBox({
@required this.title,
@required this.number,
@required this.color,
@required this.icon,
this.onPressed,
});
@override
Widget build(BuildContext context) {
return Flexible(
child: GestureDetector(
onTap: onPressed,
child: Container(
padding: EdgeInsets.all(15),
width: double.infinity,
decoration: BoxDecoration(
borderRadius: kBoxesRadius,
color: kBoxLightColor,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
CircleAvatar(
radius: 15,
backgroundColor: color,
child: icon,
),
SizedBox(width: 5),
number == 0
? SpinKitFadingCircle(
itemBuilder: (BuildContext context, int index) {
return DecoratedBox(
decoration: BoxDecoration(
color: color,
),
);
},
)
: Text(
'$number',
style:
TextStyle(fontSize: 25, fontWeight: FontWeight.bold, color: Colors.black),
textAlign: TextAlign.end,
),
],
),
SizedBox(height: 10),
Text(
title,
style: TextStyle(fontSize: 15, color: Colors.black),
)
],
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/widgets/widgets.dart | import 'package:flutter/material.dart';
import 'package:tojuwa/screens/article_screen.dart';
Widget MyAppBar() {
return AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Toju",
style: TextStyle(color: Colors.black87, fontWeight: FontWeight.w600),
),
Text(
"Wa",
style: TextStyle(color: Colors.blue, fontWeight: FontWeight.w600),
)
],
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.share),
onPressed: null,
)
],
backgroundColor: Colors.transparent,
elevation: 0.0,
);
}
class NewsTile extends StatelessWidget {
final String imgUrl, title, desc, content, posturl;
NewsTile({this.imgUrl, this.desc, this.title, this.content, @required this.posturl});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
Navigator.push(context, MaterialPageRoute(
builder: (context) => ArticleView(
postUrl: posturl,
)
));
},
child: Container(
margin: EdgeInsets.only(bottom: 24),
width: MediaQuery.of(context).size.width,
child: Container(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16),
alignment: Alignment.bottomCenter,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(bottomRight: Radius.circular(6),bottomLeft: Radius.circular(6))
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Image.network(
imgUrl,
height: 200,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
)),
SizedBox(height: 12,),
Text(
title,
maxLines: 2,
style: TextStyle(
// color: Colors.black87,
fontSize: 20,
fontWeight: FontWeight.w500),
),
SizedBox(
height: 4,
),
Text(
desc,
maxLines: 2,
style: TextStyle( fontSize: 14),
)
],
),
),
)),
);
}
} | 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/widgets/dev_scaffold.dart | import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:dynamic_theme/dynamic_theme.dart';
class DevScaffold extends StatelessWidget {
final String title;
final Widget body;
final Widget tabBar;
const DevScaffold(
{Key key, @required this.body, @required this.title, this.tabBar})
: super(key: key);
@override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: Duration(milliseconds: 500),
child: SafeArea(
top: false,
bottom: false,
child: Scaffold(
appBar: AppBar(
title: Text(title),
elevation: 0,
centerTitle: true,
bottom: tabBar != null ? tabBar : null,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.lightbulb_outline,
),
onPressed: () {
DynamicTheme.of(context).setBrightness(
Theme.of(context).brightness == Brightness.dark
? Brightness.light
: Brightness.dark);
print('changed theme!');
},
),
IconButton(
icon: Icon(
Icons.share,
),
onPressed: () {
Share.share(
"Download the Covid-19 Awareness App and share with your friends and loved ones.\nAwareness App - https://bit.ly/releasetojuwa");
},
),
]),
body: body,
),
),
);
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/models/chart_data.dart | import 'package:charts_flutter/flutter.dart' as charts;
class ChartData {
final String name;
final int amount;
charts.Color barColor;
ChartData({
this.name,
this.amount,
this.barColor,
});
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/models/coviddata.dart | class Covid{
String confirmed;
String recovered;
String deaths;
Covid({this.confirmed,this.recovered,this.deaths});
} | 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/models/article.dart | class Article {
String title;
String author;
String description;
String urlToImage;
DateTime publshedAt;
String content;
String articleUrl;
Article(
{this.title,
this.description,
this.author,
this.content,
this.publshedAt,
this.urlToImage,
this.articleUrl});
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/utils/help_line.dart | import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
class HelpData {
List<Help> helplines;
HelpData({this.helplines});
HelpData.fromJson(Map<String, dynamic> json) {
if (json['helplines'] != null) {
helplines = new List<Help>();
json['helplines'].forEach((v) {
helplines.add(Help.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.helplines != null) {
data['helplines'] = this.helplines.map((v) => v.toJson()).toList();
}
return data;
}
}
class Help {
String name;
String desc;
String image;
String subtitle;
Icon icon;
IconButton onPressed;
Help({
this.name,
this.desc,
this.subtitle,
this.image,
this.icon,
this.onPressed,
});
Help.fromJson(Map<String, dynamic> json) {
name = json['name'];
desc = json['desc'];
subtitle = json['desc'];
image = json['image'];
icon = json['icon'];
onPressed = json['onPressed'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['desc'] = this.desc;
data['subtitle'] = this.subtitle;
data['image'] = this.image;
data['icon'] = this.icon;
data['onPressed'] = this.onPressed;
return data;
}
}
List<Help> helplines = [
Help(
name: "NCDC",
desc: "Send 'hi' to ncdc on whatsapp",
subtitle: "Get info on covid-19",
image: "https://ncdc.gov.ng/themes/common/imgs/logo.jpg",
onPressed: IconButton(
color: Colors.green,
icon: Icon(
FontAwesomeIcons.whatsapp,
size: 50.0,
),
onPressed: () => launchWhatsappNcdc(),
),
),
Help(
name: "NCDC",
desc: "Call Ncdc helpline toll free",
subtitle: "Get info on covid-19",
image: "https://ncdc.gov.ng/themes/common/imgs/logo.jpg",
onPressed: IconButton(
color: Colors.green,
icon: Icon(
FontAwesomeIcons.phoneAlt,
size: 50.0,
),
onPressed: () => callNcdc(),
),
),
Help(
name: "W.H.O",
desc: "Send 'hi' to who on whatsapp",
subtitle: "Get authentic info on covid-19",
image: "https://www.who.int/images/default-source/default-album/who-emblem-rgb.png?sfvrsn=39f388cd_0",
onPressed: IconButton(
color: Colors.green,
icon: Icon(
FontAwesomeIcons.whatsapp,
size: 50.0,
),
onPressed: () => launchWhatsappWho(),
),
),
];
Future<void> launchWhatsappNcdc() async {
const url = 'https://api.whatsapp.com/send?phone=07087110839&text=Hi';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Future<void> callNcdc() async {
const url = 'tel://080097000010';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Future<void> launchWhatsappWho() async {
const url = 'https://api.whatsapp.com/send?phone=41798931892&text=Hi';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
// NCDC toll free number 080097000010 | 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/utils/pie_chart.dart | import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:tojuwa/models/chart_data.dart';
class PieChart extends StatelessWidget {
final List<ChartData> data;
PieChart({this.data});
@override
Widget build(BuildContext context) {
List<charts.Series<ChartData, String>> series = [
charts.Series(
id: "Data",
data: data,
domainFn: (ChartData series, _) => series.name,
measureFn: (ChartData series, _) => series.amount,
colorFn: (ChartData series, _) => series.barColor,
)
];
return Container(
height: 300,
padding: EdgeInsets.all(20),
child: Card(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Expanded(
child: charts.PieChart(
series,
animate: true,
defaultInteractions: true,
behaviors: [
new charts.DatumLegend(
outsideJustification: charts.OutsideJustification.endDrawArea,
horizontalFirst: false,
desiredMaxRows: 2,
cellPadding: new EdgeInsets.only(right: 4.0, bottom: 4.0),
entryTextStyle: charts.TextStyleSpec(
color: charts.MaterialPalette.purple.shadeDefault,
fontFamily: 'Georgia',
fontSize: 11),
)
],
defaultRenderer: new charts.ArcRendererConfig(
// arcLength: 4 * pi,
// arcWidth: 60,
arcRendererDecorators: [new charts.ArcLabelDecorator()],
// arcRendererDecorators: [
// new charts.ArcLabelDecorator(
// labelPosition: charts.ArcLabelPosition.inside)
// ],
),
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/utils/bar_chart.dart | import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:tojuwa/models/chart_data.dart';
class BarChart extends StatelessWidget {
final List<ChartData> data;
BarChart({this.data});
@override
Widget build(BuildContext context) {
List<charts.Series<ChartData, String>> series = [
charts.Series(
id: "Data",
data: data,
domainFn: (ChartData series, _) => series.name,
measureFn: (ChartData series, _) => series.amount,
colorFn: (ChartData series, _) => series.barColor,
)
];
return Container(
height: 300,
padding: EdgeInsets.all(20),
child: Card(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Expanded(
child: charts.BarChart(
series,
defaultInteractions: true,
animate: true,
behaviors: [
new charts.DatumLegend(
outsideJustification: charts.OutsideJustification.endDrawArea,
horizontalFirst: false,
desiredMaxRows: 2,
cellPadding: new EdgeInsets.only(right: 4.0, bottom: 4.0),
entryTextStyle: charts.TextStyleSpec(
color: charts.MaterialPalette.purple.shadeDefault,
fontFamily: 'Georgia',
fontSize: 11),
)
],
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/utils/constants.dart | import 'package:flutter/material.dart';
Color kBoxDarkColor = Color(0xFF1C1B32);
Color kBoxLightColor = Colors.white;
BorderRadius kBoxesRadius = BorderRadius.circular(10);
ThemeData kDarkTheme = ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.black,
scaffoldBackgroundColor: Colors.black,
);
ThemeData kLightTheme = ThemeData(
brightness: Brightness.light,
primaryColor: Colors.grey[100],
scaffoldBackgroundColor: Colors.grey[100],
); | 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/utils/tools.dart | import 'package:flutter/material.dart';
class Tools {
static Color hexToColor(String code) {
return Color(int.parse(code.substring(1, 7), radix: 16) + 0xFF000000);
}
static List<Color> multiColors = [
Colors.red,
Colors.amber,
Colors.green,
Colors.blue,
];
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/screens/statistics.dart | import 'package:flutter/material.dart';
import 'package:tojuwa/utils/bar_chart.dart';
import 'package:tojuwa/utils/pie_chart.dart';
import 'package:tojuwa/models/chart_data.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/animation.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:date_format/date_format.dart';
import 'package:tojuwa/widgets/dev_scaffold.dart';
class Statistics extends StatefulWidget {
@override
_StatisticsState createState() => _StatisticsState();
}
class _StatisticsState extends State<Statistics> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
String totalTested;
int totalCases = 0;
int deaths = 0;
int recovered = 0;
double fatality = 0;
double recovery = 0;
int admissions = 0;
bool _isFetching = false;
var _allData;
final List<ChartData> _chartData = [];
final List<ChartData> _pieData = [];
void _fetchChartData() async {
if (!_isFetching) {
setState(() {
_isFetching = true;
});
final response =
await http.get("https://covid9ja.herokuapp.com/api/confirmed/");
print(response.statusCode);
if (response.statusCode == 200) {
setState(() {
_allData = json.decode(response.body);
totalTested = _allData[0]['values'];
totalCases = int.tryParse(_allData[1]['values']);
deaths = int.tryParse(_allData[3]['values']);
recovered = int.tryParse(_allData[2]['values']);
fatality = double.parse(
((deaths.toDouble() * 100) / totalCases.toDouble())
.toStringAsFixed(2));
recovery = double.parse(
((recovered.toDouble() * 100) / totalCases.toDouble())
.toStringAsFixed(2));
admissions = totalCases - recovered - deaths;
_chartData.insert(
0,
ChartData(
name: "Cases",
amount: totalCases,
barColor: charts.ColorUtil.fromDartColor(Colors.blue)));
_chartData.insert(
1,
ChartData(
name: "Recovered",
amount: recovered,
barColor: charts.ColorUtil.fromDartColor(Colors.green)));
_chartData.insert(
2,
ChartData(
name: "Deaths",
amount: deaths,
barColor: charts.ColorUtil.fromDartColor(Colors.red)));
_pieData.insert(
0,
ChartData(
name: "Recovered",
amount: recovered,
barColor: charts.ColorUtil.fromDartColor(Colors.green)));
_pieData.insert(
1,
ChartData(
name: "Admitted",
amount: totalCases - recovered - deaths,
barColor: charts.ColorUtil.fromDartColor(Colors.blue)));
_pieData.insert(
2,
ChartData(
name: "Deaths",
amount: deaths,
barColor: charts.ColorUtil.fromDartColor(Colors.red)));
_isFetching = false;
});
} else {
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text("Make sure you have internet connection.",
style: TextStyle(color: Colors.white)),
backgroundColor: Colors.orange,
action: SnackBarAction(
textColor: Colors.white,
label: "Try Again",
onPressed: _fetchChartData,
),
));
}
}
}
_timestampToDate() {
var date = new DateTime.now();
var fd =
formatDate(date, [MM, " ", d, ", ", yyyy, ", ", HH, ":", nn, " ", am]);
return fd;
}
@override
void initState() {
super.initState();
_fetchChartData();
}
@override
Widget build(BuildContext context) {
return DevScaffold(
key: _scaffoldKey,
title: "Stats Area",
body: SafeArea(
child: Center(
child: Container(
child: ListView(
children: _isFetching
? <Widget>[
Center(
child: SizedBox(
child: CircularProgressIndicator(
strokeWidth: 5.0,
valueColor:
AlwaysStoppedAnimation<Color>(Colors.blue),
),
height: 50.0,
width: 50.0,
),
),
]
: <Widget>[
SizedBox(
height: 5.0,
),
Center(
child: Text(
"Cases in Nigeria",
style: TextStyle(fontSize: 20.0),
),
),
BarChart(data: _chartData),
Center(
child: Text("As of " + _timestampToDate(),
style: TextStyle(fontSize: 20, color: Colors.blue)),
),
PieChart(
data: _pieData,
),
Center(
child: Text("Total Tested: $totalTested",
style: TextStyle(fontSize: 20, color: Colors.blue)),
),
Padding(
padding: const EdgeInsets.only(
left: 18.0, right: 18.0, top: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Total Cases: $totalCases",
style: TextStyle(
fontSize: 20, color: Colors.blue)),
Text("Total Admissions: $admissions",
style: TextStyle(
fontSize: 20, color: Colors.blue)),
],
),
),
Padding(
padding: const EdgeInsets.only(
left: 18.0, right: 18.0, top: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Recovered: $recovered",
style: TextStyle(
fontSize: 20, color: Colors.green)),
Text("Recovery Rate: $recovery%",
style: TextStyle(
fontSize: 20, color: Colors.green)),
],
),
),
Padding(
padding: const EdgeInsets.only(
left: 18.0, right: 18.0, top: 8.0, bottom: 18.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Deaths: $deaths",
style:
TextStyle(fontSize: 20, color: Colors.red)),
Text("Fatality Rate: $fatality%",
style:
TextStyle(fontSize: 20, color: Colors.red)),
],
),
),
],
),
),
),
),
);
}
@override
void dispose() {
super.dispose();
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/screens/article_screen.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dynamic_theme/dynamic_theme.dart';
class ArticleView extends StatefulWidget {
final String postUrl;
ArticleView({@required this.postUrl});
@override
_ArticleViewState createState() => _ArticleViewState();
}
class _ArticleViewState extends State<ArticleView> {
final Completer<WebViewController> _controller =
Completer<WebViewController>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Row(
children: <Widget>[
CachedNetworkImage(
imageUrl:
"https://img.icons8.com/dusk/64/000000/activity-feed-2.png"),
Text(
"Corona",
style:
TextStyle(color: Colors.redAccent, fontWeight: FontWeight.w600),
),
Text(
"News",
style: TextStyle(color: Colors.blue, fontWeight: FontWeight.w600),
)
],
),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.lightbulb_outline,
),
onPressed: () {
DynamicTheme.of(context).setBrightness(
Theme.of(context).brightness == Brightness.dark
? Brightness.light
: Brightness.dark);
print('changed theme!');
},
),
IconButton(
icon: Icon(
Icons.share,
),
onPressed: () {
Share.share(
"Download the Covid-19 Awareness App and share with your friends and loved ones.\nAwareness App - https://bit.ly/releasetojuwa");
},
),
],
elevation: 0,
),
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: WebView(
initialUrl: widget.postUrl,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
),
),
);
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/screens/precautions.dart | import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:tojuwa/widgets/dev_scaffold.dart';
import 'package:url_launcher/url_launcher.dart';
class Measures extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DevScaffold(
title: 'Protective measures',
body: FutureBuilder(
future: DefaultAssetBundle.of(context)
.loadString("assets/docs/protective_measures.md"),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return Markdown(
onTapLink: (url) {
launch(url);
},
data: snapshot.data,
styleSheet: MarkdownStyleSheet(
textAlign: WrapAlignment.start,
p: TextStyle(
fontSize: 16,
color: Colors.black,
),
h2: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black,
),
h1: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
color: Colors.black,
),
h3: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.black,
),
a: TextStyle(
decoration: TextDecoration.underline,
color: Colors.blue,
),
),
);
}
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.blue,
strokeWidth: 5,
),
);
},
),
);
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/screens/news_screen.dart | import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:tojuwa/network/newsdata.dart';
import 'package:tojuwa/widgets/widgets.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dynamic_theme/dynamic_theme.dart';
class CoronaNews extends StatefulWidget {
@override
_CoronaNewsState createState() => _CoronaNewsState();
}
class _CoronaNewsState extends State<CoronaNews> {
var newslist;
bool _loading = true;
@override
void initState() {
getNews();
// TODO: implement initState
super.initState();
}
void getNews() async {
NewsForCorona news = NewsForCorona();
await news.getNewsForCorona();
newslist = news.news;
setState(() {
_loading = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Row(
children: <Widget>[
CachedNetworkImage(
imageUrl:
"https://img.icons8.com/dusk/64/000000/activity-feed-2.png"),
Text(
"Corona",
style: TextStyle(
color: Colors.redAccent, fontWeight: FontWeight.w600),
),
Text(
"News",
style: TextStyle(color: Colors.blue, fontWeight: FontWeight.w600),
)
],
),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.lightbulb_outline,
),
onPressed: () {
DynamicTheme.of(context).setBrightness(
Theme.of(context).brightness == Brightness.dark
? Brightness.light
: Brightness.dark);
print('changed theme!');
},
),
IconButton(
icon: Icon(
Icons.share,
),
onPressed: () {
Share.share(
"Download the Covid-19 Awareness App and share with your friends and loved ones.\nAwareness App - https://bit.ly/releasetojuwa");
},
),
],
elevation: 0,
),
body: _loading
? Center(
child: CircularProgressIndicator(),
)
: SingleChildScrollView(
child: Container(
child: Container(
margin: EdgeInsets.only(top: 16),
child: ListView.builder(
itemCount: newslist.length,
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemBuilder: (context, index) {
return NewsTile(
imgUrl: newslist[index].urlToImage ?? "",
title: newslist[index].title ?? "",
desc: newslist[index].description ?? "",
content: newslist[index].content ?? "",
posturl: newslist[index].articleUrl ?? "",
);
}),
),
),
),
);
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/screens/homepage.dart | import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:tojuwa/screens/helpline_screen.dart';
import 'package:tojuwa/screens/news_screen.dart';
import 'package:tojuwa/screens/states_screen.dart';
import 'package:tojuwa/screens/statistics.dart';
import 'package:tojuwa/utils/constants.dart';
import 'package:tojuwa/widgets/dev_scaffold.dart';
import 'package:tojuwa/widgets/info_box.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:tojuwa/screens/precautions.dart';
import 'package:http/http.dart' as http;
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int totalTested = 0;
int totalCases = 0;
int deaths = 0;
int recovered = 0;
List states = [];
Future<String> getTotalCasesForCorona() async {
String url = "https://covid9ja.herokuapp.com/api/confirmed/";
final response = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
print(response.body);
setState(() {
var data = json.decode(response.body);
totalTested = int.tryParse(data[0]['values']);
totalCases = int.tryParse(data[1]['values']);
deaths = int.tryParse(data[3]['values']);
recovered = int.tryParse(data[2]['values']);
});
return "Success";
}
Future<String> getStatesData() async {
String url = "https://covid9ja.herokuapp.com/api/states/";
final response = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
print(response.body);
setState(() {
var data = json.decode(response.body);
states = data;
});
return "Success";
}
void eventsLength() {
print(states.length);
}
@override
void initState() {
getTotalCasesForCorona();
getStatesData();
Timer.periodic(
Duration(hours: 1),
(Timer t) => getTotalCasesForCorona(),
);
Timer.periodic(
Duration(hours: 1),
(Timer t) => getStatesData(),
);
super.initState();
}
@override
Widget build(BuildContext context) {
return DevScaffold(
title: 'Toju Wa',
body: SafeArea(
child: Padding(
padding: EdgeInsets.only(top: 5, left: 10, right: 10, bottom: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Flexible(
child: ListView(
children: <Widget>[
Text(
'Nigeria',
style:
TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
),
SizedBox(height: 15),
Row(
children: <Widget>[
InfoBox(
title: 'Total cases',
number: totalCases,
color: Colors.blue,
icon: Icon(FontAwesomeIcons.globeAmericas,
color: Colors.white, size: 20),
),
SizedBox(width: 25),
InfoBox(
title: 'States Affected',
color: Colors.orange,
icon: Icon(Icons.flag, color: Colors.white),
number: states.length,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => States(
statesList: states,
// isDark: isDarkTheme,
),
),
);
},
),
],
),
SizedBox(height: 25),
Row(
children: <Widget>[
InfoBox(
title: 'Deaths',
color: Colors.red,
icon: Icon(FontAwesomeIcons.skull,
color: Colors.white, size: 20),
number: deaths,
),
SizedBox(width: 25),
InfoBox(
title: 'Recovered',
number: recovered,
color: Colors.green,
icon: Icon(Icons.check, color: Colors.white),
),
],
),
SizedBox(height: 25),
Container(
padding: EdgeInsets.symmetric(vertical: 5),
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent),
borderRadius: kBoxesRadius,
),
child: ListTile(
leading: Icon(
FontAwesomeIcons.readme,
color: Colors.blue,
),
title: Text(
'Protective measures',
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold,),
),
subtitle: Text(
'Protective measures against the coronavirus',
style: TextStyle(fontSize: 15,),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Measures()),
);
},
),
),
Container(
padding: EdgeInsets.symmetric(vertical: 5),
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent),
borderRadius: kBoxesRadius,
),
child: ListTile(
leading: Icon(
FontAwesomeIcons.newspaper,
color: Colors.blue,
),
title: Text(
'Latest News',
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold,),
),
subtitle: Text(
'Live updates about covid-19',
style: TextStyle(fontSize: 15,),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CoronaNews()),
);
},
),
),
Container(
padding: EdgeInsets.symmetric(vertical: 5),
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent),
borderRadius: kBoxesRadius,
),
child: ListTile(
leading: Icon(
FontAwesomeIcons.chartLine,
color: Colors.blue,
),
title: Text(
'Statistics',
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold,),
),
subtitle: Text(
'View the stats and trends of the infection',
style: TextStyle(fontSize: 15,),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Statistics()),
);
},
),
),
Container(
padding: EdgeInsets.symmetric(vertical: 5),
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent),
borderRadius: kBoxesRadius,
),
child: ListTile(
leading: Icon(
FontAwesomeIcons.phoneAlt,
color: Colors.blue,
),
title: Text(
'Helpline',
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold,),
),
subtitle: Text(
'Know anyone exhibiting symptoms and need help?',
style: TextStyle(fontSize: 15,),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HelpLine()),
);
},
),
),
],
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/screens/states_screen.dart | import 'package:flutter/material.dart';
import 'package:tojuwa/utils/constants.dart';
bool isPinned = false;
bool isSearching = false;
class States extends StatefulWidget {
States({this.statesList});
final List statesList;
@override
_StatesState createState() => _StatesState();
}
class _StatesState extends State<States> {
List filteredStates = [];
final searchInputController = TextEditingController();
void findState(value) {
filteredStates = widget.statesList
.where(
(state) =>
(state['state'].toLowerCase()).contains(value.toLowerCase()),
)
.toList();
// assign filteredCountries to a list of all the countries containing the entered query
}
// toggle appbar icon
GestureDetector toggleAppBarIcon() {
GestureDetector displayedIcon;
if (isSearching) {
displayedIcon = GestureDetector(
child: Icon(
Icons.cancel,
),
onTap: () {
setState(() {
isSearching = !isSearching;
filteredStates = widget.statesList;
// reassign filteredCountries to the initial value when the searchbar is collapsed
});
},
);
} else {
displayedIcon = GestureDetector(
child: Icon(
Icons.search,
),
onTap: () {
setState(() {
isSearching = !isSearching;
});
},
);
}
return displayedIcon;
}
@override
void initState() {
filteredStates = widget.statesList;
// assign countriesList to a mutable variable so that I can edit it when changing states
filteredStates.forEach((state) {
state['isFollowed'] = false;
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: isSearching
? Container(
width: double.infinity,
padding: EdgeInsets.symmetric(horizontal: 15),
decoration: BoxDecoration(
// color: widget.isDark ? kBoxDarkColor : Colors.grey[100],
borderRadius: BorderRadius.circular(30),
),
child: Row(
children: <Widget>[
Icon(Icons.search),
SizedBox(width: 15),
Expanded(
child: TextField(
controller: searchInputController,
autofocus: true,
decoration: InputDecoration.collapsed(
hintText: 'Search state...',
),
onChanged: (value) {
setState(() {
value == ''
? filteredStates = widget.statesList
: findState(
(value.toLowerCase()).capitalize(),);
});
},
),
)
],
),
)
: Text('Affected Countries'),
centerTitle: true,
actions: <Widget>[
Padding(
padding: EdgeInsets.only(right: 8.0),
child: toggleAppBarIcon(),
)
],
),
body: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: filteredStates.length,
itemBuilder: (context, index) {
var state = filteredStates[index];
return StateDetails(
// isDark: widget.isDark,
state: state,
follow: () {
setState(() {
state['isFollowed'] = !state['isFollowed'];
});
},
);
},
),
),
],
),
);
}
}
class StateDetails extends StatelessWidget {
StateDetails(
{@required this.state, @required this.follow});
final Map state;
final Function follow;
// final bool isDark;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(15),
padding: EdgeInsets.all(15),
decoration: BoxDecoration(
// color: isDark ? kBoxDarkColor : kBoxLightColor,
borderRadius: kBoxesRadius,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Image(
image: NetworkImage(state['stateInfo']['flag']),
height: 20,
width: 25,
),
Text(
state['state'].toUpperCase(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 22),
textAlign: TextAlign.center,
),
],
),
SizedBox(height: 5),
Divider(color: Colors.blueGrey[200], thickness: .5),
SizedBox(height: 15),
Text('Total cases: ${state['cases']}',
style: TextStyle(fontSize: 18)),
Text('Total in admission: ${state['admitted']}',
style: TextStyle(fontSize: 18)),
Text('Total recovered: ${state['recovered']}',
style: TextStyle(fontSize: 18)),
Text('Today deaths: ${state['deaths']}',
style: TextStyle(fontSize: 18)),
],
),
);
}
}
| 0 |
mirrored_repositories/ncovid/lib | mirrored_repositories/ncovid/lib/screens/helpline_screen.dart | import 'dart:math';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:tojuwa/utils/help_line.dart';
import 'package:tojuwa/utils/tools.dart';
import 'package:tojuwa/widgets/dev_scaffold.dart';
class HelpLine extends StatelessWidget {
@override
Widget build(BuildContext context) {
var helpline = helplines;
return DevScaffold(
title: 'Help Area',
body: ListView.builder(
shrinkWrap: true,
itemBuilder: (c, i) {
return Card(
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints.expand(
height: MediaQuery.of(context).size.height * 0.2,
width: MediaQuery.of(context).size.width * 0.3,
),
child: CachedNetworkImage(
fit: BoxFit.cover,
imageUrl: helpline[i].image,
),
),
SizedBox(
width: 20,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
helpline[i].name,
style: Theme.of(context).textTheme.title,
),
SizedBox(
height: 5,
),
AnimatedContainer(
duration: Duration(seconds: 1),
width: MediaQuery.of(context).size.width * 0.2,
height: 5,
color: Tools.multiColors[Random().nextInt(4)],
),
],
),
SizedBox(
height: 10,
),
Text(
helpline[i].desc,
style: Theme.of(context).textTheme.subtitle,
),
SizedBox(
height: 10,
),
Text(
helpline[i].subtitle,
style: Theme.of(context).textTheme.caption,
),
],
),
),
helpline[i].onPressed,
],
),
),
);
},
itemCount: helpline.length,
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Shimmer | mirrored_repositories/Flutter-Shimmer/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_shimmer/screens/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Shimmer',
debugShowCheckedModeBanner: false,
home: Home(),
);
}
}
| 0 |
mirrored_repositories/Flutter-Shimmer/lib | mirrored_repositories/Flutter-Shimmer/lib/widgets/list_widget.dart | import 'package:flutter/material.dart';
typedef Null ItemSelectedCallback(int value);
class ListWidget extends StatefulWidget {
final int count;
ListWidget(
this.count,
);
@override
_ListWidgetState createState() => _ListWidgetState();
}
class _ListWidgetState extends State<ListWidget> {
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: widget.count,
itemBuilder: (context, position) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: InkWell(
onTap: () {
print("Tapped");
},
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(position.toString(), style: TextStyle(fontSize: 22.0),),
),
],
),
),
),
);
},
);
}
}
| 0 |
mirrored_repositories/Flutter-Shimmer/lib | mirrored_repositories/Flutter-Shimmer/lib/widgets/shimmer_list.dart | import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
class ShimmerList extends StatelessWidget {
@override
Widget build(BuildContext context) {
int offset = 0;
int time = 1000;
return SafeArea(
child: ListView.builder(
itemCount: 10,
itemBuilder: (BuildContext context, int index) {
offset += 5;
time = 800 + offset;
print(time);
return Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: Shimmer.fromColors(
highlightColor: Colors.white,
baseColor: Colors.grey[350],
child: ShimmerLayout(),
period: Duration(milliseconds: time),
));
},
),
);
}
}
class ShimmerLayout extends StatelessWidget {
@override
Widget build(BuildContext context) {
double containerWidth = MediaQuery.of(context).size.width - 150;
double containerHeight = 15;
return Container(
margin: EdgeInsets.symmetric(vertical: 7.5),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
height: 100,
width: 100,
color: Colors.grey,
),
SizedBox(width: 10),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
height: containerHeight,
width: containerWidth,
color: Colors.grey,
),
SizedBox(height: 5),
Container(
height: containerHeight,
width: containerWidth,
color: Colors.grey,
),
SizedBox(height: 5),
Container(
height: containerHeight,
width: containerWidth * 0.75,
color: Colors.grey,
)
],
)
],
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Shimmer/lib | mirrored_repositories/Flutter-Shimmer/lib/screens/home.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_shimmer/widgets/list_widget.dart';
import 'package:flutter_shimmer/widgets/shimmer_list.dart';
class Home extends StatefulWidget{
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return HomeState();
}
}
class HomeState extends State<Home>{
var isDataFetched = false;
@override
void initState() {
// TODO: implement initState
super.initState();
Timer timer = Timer(Duration(seconds: 3), () {
setState(() {
isDataFetched = true;
});
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: SafeArea(child: isDataFetched == false ? ShimmerList() : ListWidget(10))
);
}
} | 0 |
mirrored_repositories/Flutter-Shimmer | mirrored_repositories/Flutter-Shimmer/test/widget_test.dart | // 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:flutter_shimmer/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);
});
}
| 0 |
mirrored_repositories | mirrored_repositories/Mobile-StatusNeo/main.dart | import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: Home()
));
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Where is Everyone'),
centerTitle: true,
backgroundColor: Colors.amber[400],
),
body: Center(
child: RaisedButton(
onPressed: (){},
child: Text('click me'),
color: Colors.blue[500],
)
),
floatingActionButton: FloatingActionButton(
child: Text('click'),
),
);
}
}
| 0 |
mirrored_repositories/Mobile-StatusNeo | mirrored_repositories/Mobile-StatusNeo/lib/main.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: Home()
));
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Where is Everyone'),
centerTitle: true,
backgroundColor: Colors.amber[400],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Text('he;;oo'),
Text ('world'),
],
),
Text('heelo'),
FlatButton(
onPressed: (){},
child: Text('clicl'),
color: Colors.amber,
),
Expanded(
child: Container(
color: Colors.greenAccent,
padding: EdgeInsets.all(40.0),
child: Text('inisde container'),
),
)
],
),
floatingActionButton: FloatingActionButton(
child: Text('click'),
),
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway | mirrored_repositories/flutter_ksubway/lib/main.dart | import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ksubway/config/routes.dart';
import 'package:flutter_ksubway/preferences/theme_preference.dart';
import 'package:flutter_ksubway/style/theme_styles.dart';
import 'config/application.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final themePreference = ThemePreference();
bool isDarkTheme = await themePreference.getTheme();
MyApp.themeNotifier.value = isDarkTheme == true ? ThemeMode.dark : ThemeMode.light;
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
static final ValueNotifier<ThemeMode> themeNotifier = ValueNotifier(ThemeMode.light);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
_MyAppState() {
final router = FluroRouter();
Routes.configureRoutes(router);
Application.router = router;
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<ThemeMode>(
valueListenable: MyApp.themeNotifier,
builder: (_, ThemeMode currentMode, __) {
return MaterialApp(
title: 'K-SUBWAY',
theme: lightTheme,
darkTheme: darkTheme,
themeMode: currentMode,
onGenerateRoute: Application.router.generator,
);
},
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/components/subway_line_button.dart | import 'package:flutter/material.dart';
import 'package:flutter_ksubway/main.dart';
import 'package:flutter_ksubway/style/textStyles.dart';
class SubwayLineButton extends StatelessWidget {
const SubwayLineButton({
Key? key,
required this.animationControllerList,
required this.lineNumTitles,
required this.lineNumColors,
required this.index,
}) : super(key: key);
final List<AnimationController> animationControllerList;
final List<String> lineNumTitles;
final List<Color> lineNumColors;
final int index;
@override
Widget build(BuildContext context) {
return Transform.scale(
scale: 1 - animationControllerList[index].value,
child: Container(
margin: const EdgeInsets.fromLTRB(8, 0, 4, 12),
child: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
child: Center(
child: Text(lineNumTitles[index], style: textStyleSub1.copyWith(fontSize: 14)),
),
),
decoration: BoxDecoration(
color: MyApp.themeNotifier.value == ThemeMode.light ? Colors.white : lineNumColors[index].withAlpha(40),
border: Border.all(width: 2, color: lineNumColors[index]),
borderRadius: BorderRadius.circular(16.0),
boxShadow: [
BoxShadow(
color: MyApp.themeNotifier.value == ThemeMode.light ? Colors.grey : Colors.black,
offset: const Offset(0.0, 4.0), //(x,y)
blurRadius: 4.0,
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/components/subway_info.dart | import 'package:flutter/material.dart';
import 'package:flutter_ksubway/main.dart';
import 'package:flutter_ksubway/models/exp_ksubway_info.dart';
import 'package:flutter_ksubway/style/textStyles.dart';
import 'package:marquee/marquee.dart';
class SubwayInfo extends StatelessWidget {
const SubwayInfo({
Key? key,
required this.subwayInfoScrollController,
required this.ttcVOList,
required this.lineNumColors,
required this.lineNumPageIndex,
}) : super(key: key);
final ScrollController subwayInfoScrollController;
final List<TtcVOList> ttcVOList;
final List<Color> lineNumColors;
final int lineNumPageIndex;
@override
Widget build(BuildContext context) {
return Expanded(
child: AnimatedContainer(
margin: const EdgeInsets.fromLTRB(8, 0, 8, 12),
// 지하철 정보 뜨는 곳
child: ttcVOList.isEmpty
? const Center(
child: Text(
'정보를 불러오지 못했어요',
style: textStyleSub1,
),
)
: ListView.builder(
controller: subwayInfoScrollController,
itemCount: ttcVOList.length,
itemBuilder: ((context, index) {
String subwayNum = "";
String carNum = "";
String direction = "";
String status = "";
String currStation = "";
Color statusColor = Colors.white;
subwayNum = ttcVOList[index].trainY! == "null" ? "정보없음" : ttcVOList[index].trainY!;
carNum = ttcVOList[index].trainP! == "null" ? "정보없음" : ttcVOList[index].trainP!;
subwayNum = ttcVOList[index].trainY! == "null" ? "정보없음" : ttcVOList[index].trainY!;
direction = ttcVOList[index].statnTnm! == "null" ? "정보없음" : ttcVOList[index].statnTnm!.replaceAll("(", "\n(") + "행";
status = ttcVOList[index].sts! == "null" ? "-" : ttcVOList[index].sts!;
currStation = ttcVOList[index].stationNm! == "null" ? "-" : ttcVOList[index].stationNm!;
if (status == "1") {
statusColor = Colors.green;
status = "접근";
}
if (status == "2") {
statusColor = Colors.cyan;
status = "도착";
}
if (status == "3") {
statusColor = MyApp.themeNotifier.value == ThemeMode.light ? Colors.yellow : const Color.fromARGB(255, 153, 141, 34);
status = "출발";
}
if (status == "4") {
statusColor = Colors.red;
status = "통과";
}
return AnimatedContainer(
padding: const EdgeInsets.symmetric(vertical: 16),
margin: ttcVOList.length - 1 != index ? const EdgeInsets.fromLTRB(16, 16, 16, 0) : const EdgeInsets.fromLTRB(16, 16, 16, 16),
child: Row(
children: [
Column(
children: [
Container(
width: 90, // 장평이 안맞아서 가로 길이 고정
child: Center(
child: Text(
subwayNum,
style: textStyleSub1,
textAlign: TextAlign.center,
),
),
color: lineNumColors[lineNumPageIndex],
),
Container(
width: 90, // 장평이 안맞아서 가로 길이 고정
child: Center(
child: Text(
direction,
style: textStyleSub1,
textAlign: TextAlign.center,
),
),
color: lineNumColors[lineNumPageIndex].withAlpha(100),
),
],
),
Container(height: 50, width: 1, color: Colors.grey),
const SizedBox(
width: 8,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
"CAR # $carNum",
style: textStyleSub1,
),
SizedBox(
height: 20,
child: Row(
children: [
Expanded(
child: Container(
child: Center(
child: currStation.length > 4
? Marquee(
text: currStation,
style: textStyleSub1,
blankSpace: 25,
velocity: 25,
)
: Text(
currStation,
style: textStyleSub1,
),
),
color: lineNumColors[lineNumPageIndex].withAlpha(100),
),
),
Expanded(
child: Container(
child: Center(
child: Text(
status,
style: textStyleSub1,
textAlign: TextAlign.center,
),
),
color: statusColor,
),
),
],
),
),
],
),
),
],
),
duration: const Duration(milliseconds: 220),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(8)),
color: MyApp.themeNotifier.value == ThemeMode.light ? Colors.white : Color.fromARGB(255, 52, 86, 97),
boxShadow: [
BoxShadow(
color: Color.fromARGB(255, 32, 32, 32),
offset: const Offset(5.0, 4.0),
blurRadius: 12.0,
),
],
),
);
}),
),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(8)),
color: lineNumColors[lineNumPageIndex],
boxShadow: [
BoxShadow(
color: MyApp.themeNotifier.value == ThemeMode.light ? Colors.grey : Color.fromARGB(255, 34, 34, 34),
offset: const Offset(5.0, 8.0),
blurRadius: 24.0,
),
],
),
duration: const Duration(milliseconds: 220),
),
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/components/app_title.dart | import 'package:flutter/material.dart';
import 'package:flutter_ksubway/style/textStyles.dart';
class AppTitle extends StatelessWidget {
const AppTitle({
Key? key,
required this.title,
}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
title,
style: textStyleTitle,
),
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/models/ksubway_arrinfo.dart | class KsubwayArrinfo {
ErrorMessage? errorMessage;
List<RealtimeArrivalList>? realtimeArrivalList;
KsubwayArrinfo({this.errorMessage, this.realtimeArrivalList});
KsubwayArrinfo.fromJson(Map<String, dynamic> json) {
errorMessage = json['errorMessage'] != null ? ErrorMessage.fromJson(json['errorMessage']) : null;
if (json['realtimeArrivalList'] != null) {
realtimeArrivalList = <RealtimeArrivalList>[];
json['realtimeArrivalList'].forEach((v) {
realtimeArrivalList!.add(RealtimeArrivalList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (this.errorMessage != null) {
data['errorMessage'] = this.errorMessage!.toJson();
}
if (this.realtimeArrivalList != null) {
data['realtimeArrivalList'] = this.realtimeArrivalList!.map((v) => v.toJson()).toList();
}
return data;
}
}
class ErrorMessage {
String? status;
String? code;
String? message;
String? link;
String? developerMessage;
String? total;
ErrorMessage({this.status, this.code, this.message, this.link, this.developerMessage, this.total});
ErrorMessage.fromJson(Map<String, dynamic> json) {
status = json['status'].toString();
code = json['code'].toString();
message = json['message'].toString();
link = json['link'].toString();
developerMessage = json['developerMessage'].toString();
total = json['total'].toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = this.status;
data['code'] = this.code;
data['message'] = this.message;
data['link'] = this.link;
data['developerMessage'] = this.developerMessage;
data['total'] = this.total;
return data;
}
}
class RealtimeArrivalList {
String? beginRow;
String? endRow;
String? curPage;
String? pageRow;
String? totalCount;
String? rowNum;
String? selectedCount;
String? subwayId;
String? subwayNm;
String? updnLine;
String? trainLineNm;
String? subwayHeading;
String? statnFid;
String? statnTid;
String? statnId;
String? statnNm;
String? trainCo;
String? ordkey;
String? subwayList;
String? statnList;
String? btrainSttus;
String? barvlDt;
String? btrainNo;
String? bstatnId;
String? bstatnNm;
String? recptnDt;
String? arvlMsg2;
String? arvlMsg3;
String? arvlCd;
RealtimeArrivalList({this.beginRow, this.endRow, this.curPage, this.pageRow, this.totalCount, this.rowNum, this.selectedCount, this.subwayId, this.subwayNm, this.updnLine, this.trainLineNm, this.subwayHeading, this.statnFid, this.statnTid, this.statnId, this.statnNm, this.trainCo, this.ordkey, this.subwayList, this.statnList, this.btrainSttus, this.barvlDt, this.btrainNo, this.bstatnId, this.bstatnNm, this.recptnDt, this.arvlMsg2, this.arvlMsg3, this.arvlCd});
RealtimeArrivalList.fromJson(Map<String, dynamic> json) {
beginRow = json['beginRow'].toString();
endRow = json['endRow'].toString();
curPage = json['curPage'].toString();
pageRow = json['pageRow'].toString();
totalCount = json['totalCount'].toString();
rowNum = json['rowNum'].toString();
selectedCount = json['selectedCount'].toString();
subwayId = json['subwayId'].toString();
subwayNm = json['subwayNm'].toString();
updnLine = json['updnLine'].toString();
trainLineNm = json['trainLineNm'].toString();
subwayHeading = json['subwayHeading'].toString();
statnFid = json['statnFid'].toString();
statnTid = json['statnTid'].toString();
statnId = json['statnId'].toString();
statnNm = json['statnNm'].toString();
trainCo = json['trainCo'].toString();
ordkey = json['ordkey'].toString();
subwayList = json['subwayList'].toString();
statnList = json['statnList'].toString();
btrainSttus = json['btrainSttus'].toString();
barvlDt = json['barvlDt'].toString();
btrainNo = json['btrainNo'].toString();
bstatnId = json['bstatnId'].toString();
bstatnNm = json['bstatnNm'].toString();
recptnDt = json['recptnDt'].toString();
arvlMsg2 = json['arvlMsg2'].toString();
arvlMsg3 = json['arvlMsg3'].toString();
arvlCd = json['arvlCd'].toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['beginRow'] = this.beginRow;
data['endRow'] = this.endRow;
data['curPage'] = this.curPage;
data['pageRow'] = this.pageRow;
data['totalCount'] = this.totalCount;
data['rowNum'] = this.rowNum;
data['selectedCount'] = this.selectedCount;
data['subwayId'] = this.subwayId;
data['subwayNm'] = this.subwayNm;
data['updnLine'] = this.updnLine;
data['trainLineNm'] = this.trainLineNm;
data['subwayHeading'] = this.subwayHeading;
data['statnFid'] = this.statnFid;
data['statnTid'] = this.statnTid;
data['statnId'] = this.statnId;
data['statnNm'] = this.statnNm;
data['trainCo'] = this.trainCo;
data['ordkey'] = this.ordkey;
data['subwayList'] = this.subwayList;
data['statnList'] = this.statnList;
data['btrainSttus'] = this.btrainSttus;
data['barvlDt'] = this.barvlDt;
data['btrainNo'] = this.btrainNo;
data['bstatnId'] = this.bstatnId;
data['bstatnNm'] = this.bstatnNm;
data['recptnDt'] = this.recptnDt;
data['arvlMsg2'] = this.arvlMsg2;
data['arvlMsg3'] = this.arvlMsg3;
data['arvlCd'] = this.arvlCd;
return data;
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/models/ksubway_seoulstations.dart | class KsubwaySeoulstations {
List<StationList>? stationList;
KsubwaySeoulstations({this.stationList});
KsubwaySeoulstations.fromJson(Map<String, dynamic> json) {
if (json['stationList'] != null) {
stationList = <StationList>[];
json['stationList'].forEach((v) {
stationList!.add(new StationList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.stationList != null) {
data['stationList'] = this.stationList!.map((v) => v.toJson()).toList();
}
return data;
}
}
class StationList {
int? subwayId;
int? statnId;
String? statnNm;
StationList({this.subwayId, this.statnId, this.statnNm});
StationList.fromJson(Map<String, dynamic> json) {
subwayId = int.parse(json['SUBWAY_ID'].toString().split(".")[0]);
statnId = int.parse(json['STATN_ID'].toString().split(".")[0]);
statnNm = json['STATN_NM'].toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['SUBWAY_ID'] = this.subwayId;
data['STATN_ID'] = this.statnId;
data['STATN_NM'] = this.statnNm;
return data;
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/models/exp_ksubway_info.dart | class ExpksubwayInfo {
bool? isValid;
List<TtcVOList>? ttcVOList;
ExpksubwayInfo({this.isValid, this.ttcVOList});
ExpksubwayInfo.fromJson(Map<String, dynamic> json) {
isValid = json['isValid'];
if (json['ttcVOList'] != null) {
ttcVOList = <TtcVOList>[];
json['ttcVOList'].forEach((v) {
ttcVOList!.add(TtcVOList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['isValid'] = this.isValid;
if (this.ttcVOList != null) {
data['ttcVOList'] = this.ttcVOList!.map((v) => v.toJson()).toList();
}
return data;
}
}
class TtcVOList {
String? trainY;
String? trainP;
String? sts;
String? dir;
String? line;
String? stationCd;
String? stationNm;
String? statnTnm;
String? directAt;
String? lineGbn;
TtcVOList({this.trainY, this.trainP, this.sts, this.dir, this.line, this.stationCd, this.stationNm, this.statnTnm, this.directAt, this.lineGbn});
TtcVOList.fromJson(Map<String, dynamic> json) {
trainY = json['trainY'].toString();
trainP = json['trainP'].toString();
sts = json['sts'].toString();
dir = json['dir'].toString();
line = json['line'].toString();
stationCd = json['stationCd'].toString();
stationNm = json['stationNm'].toString();
statnTnm = json['statnTnm'].toString();
directAt = json['directAt'].toString();
lineGbn = json['lineGbn'].toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['trainY'] = this.trainY;
data['trainP'] = this.trainP;
data['sts'] = this.sts;
data['dir'] = this.dir;
data['line'] = this.line;
data['stationCd'] = this.stationCd;
data['stationNm'] = this.stationNm;
data['statnTnm'] = this.statnTnm;
data['directAt'] = this.directAt;
data['lineGbn'] = this.lineGbn;
return data;
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/config/routes.dart | import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ksubway/config/handler.dart';
import 'package:flutter_ksubway/screens/notfound_screen.dart';
class Routes {
static String root = "/";
static String expScreen = "/exp";
static String settingScreen = "/setting";
static String arrinfoScreen = "/arrinfo/:stationName";
static void configureRoutes(FluroRouter router) {
router.notFoundHandler = Handler(handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return const NotFoundScreen();
});
router.define(root, handler: rootHandler);
router.define(expScreen, handler: expScreenHandler);
router.define(settingScreen, handler: settingScreenHandler);
router.define(arrinfoScreen, handler: arrinfoScreenHandler);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/config/handler.dart | import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ksubway/screens/arrinfo_screen.dart';
import 'package:flutter_ksubway/screens/exp_screen.dart';
import 'package:flutter_ksubway/screens/home_screen.dart';
import 'package:flutter_ksubway/screens/setting_screen.dart';
var rootHandler = Handler(handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return const HomeScreen();
});
var expScreenHandler = Handler(handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return const ExpScreen();
});
var settingScreenHandler = Handler(handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
return const SettingScreen();
});
var arrinfoScreenHandler = Handler(handlerFunc: (BuildContext? context, Map<String, dynamic> params) {
return ArrInfoScreen(params["stationName"][0]);
});
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/config/application.dart | import 'package:fluro/fluro.dart';
class Application {
static late final FluroRouter router;
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/preferences/exp_api_preference.dart | import 'package:shared_preferences/shared_preferences.dart';
class ExpApiPreference {
static const expApiEndpoint = "exp_api_endpoint";
setApiEndpoint(String value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(expApiEndpoint, value);
}
Future<String> getApiEndpoint() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(expApiEndpoint) ?? "demo";
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/preferences/ksubway_stations_preference.dart | import 'dart:convert';
import 'package:flutter_ksubway/models/ksubway_seoulstations.dart';
import 'package:shared_preferences/shared_preferences.dart';
class KsubwayStationsPreference {
static const seoulStations = "seoul_stations";
setSeoulstations(KsubwaySeoulstations value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final _v = const JsonEncoder.withIndent(null).convert(value.toJson());
prefs.setString(seoulStations, _v);
}
Future<KsubwaySeoulstations> getSeoulstations() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return KsubwaySeoulstations.fromJson(
json.decode(
prefs.getString(seoulStations) ?? '{"stationList":[]}',
),
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/preferences/theme_preference.dart | import 'package:shared_preferences/shared_preferences.dart';
class ThemePreference {
static const themeStatus = "theme_status";
setDarkTheme(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool(themeStatus, value);
}
Future<bool> getTheme() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(themeStatus) ?? false;
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/services/exp_ksubway_api.dart | import 'package:flutter/services.dart';
import 'package:flutter_ksubway/models/exp_ksubway_info.dart';
import 'package:flutter_ksubway/preferences/exp_api_preference.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class ExpksubwayApi {
Future<ExpksubwayInfo> fetchExpksubwayInfo(String lineNumCd) async {
final expApiPreference = ExpApiPreference();
String _uri = await expApiPreference.getApiEndpoint();
if (_uri == "demo") {
String data = await rootBundle.loadString('data/exp_ksubway_api/demo.json');
return ExpksubwayInfo.fromJson(json.decode(data)[lineNumCd]);
}
final response = await http.post(
Uri.parse(_uri + "?lineNumCd=" + lineNumCd),
);
if (response.statusCode == 200) {
return ExpksubwayInfo.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load subway data');
}
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/services/ksubway_api.dart | import 'dart:developer';
import 'package:flutter_ksubway/models/ksubway_arrinfo.dart';
import 'package:flutter_ksubway/models/ksubway_seoulstations.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class KsubwayApi {
static Future<KsubwayArrinfo> fetchKsubwayArrinfo({required String startPage, required String endPage, required String realtimeType, required String stationName}) async {
String _serviceKey = const String.fromEnvironment("swopenapi_seoul_subway_key");
final response = await http.get(
Uri.parse('http://swopenapi.seoul.go.kr/api/subway/$_serviceKey/json/$realtimeType/$startPage/$endPage/$stationName'),
);
if ((response.statusCode == 200 || response.statusCode == 405) && response.body.isNotEmpty) {
KsubwayArrinfo _result = KsubwayArrinfo.fromJson(json.decode(response.body));
if (json.decode(response.body)["code"] == "ERROR-337") {
log('Exceed request API Key (replaced by sample key)');
final _response = await http.get(
Uri.parse('http://swopenapi.seoul.go.kr/api/subway/sample/json/$realtimeType/0/5/$stationName'),
);
_result = KsubwayArrinfo.fromJson(json.decode(_response.body));
}
return _result;
} else {
throw Exception('Failed to load subway data');
}
}
static Future<dynamic> fetchKsubwayStations({required String city}) async {
final response = await http.get(
Uri.parse('https://raw.githubusercontent.com/dart-bird/korea-subway-stations/main/${city}_stations.json'),
);
if (response.statusCode == 200) {
final result = KsubwaySeoulstations.fromJson(json.decode(response.body));
return result;
} else {
throw Exception('Failed to load subway station data');
}
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/screens/home_screen.dart | import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ksubway/config/application.dart';
import 'package:flutter_ksubway/main.dart';
import 'package:flutter_ksubway/models/ksubway_seoulstations.dart';
import 'package:flutter_ksubway/preferences/ksubway_stations_preference.dart';
import 'package:flutter_ksubway/services/ksubway_api.dart';
import 'package:flutter_ksubway/style/textStyles.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<StationList> stationSuggestions = [];
KsubwaySeoulstations ksubwaySeoulstations = KsubwaySeoulstations(stationList: []);
final List<String?> seoulstations = [];
final TextEditingController _searchStationTextEditingController = TextEditingController();
final KsubwayStationsPreference _ksubwayStationsPreference = KsubwayStationsPreference();
void fetchKsubwayStations() async {
ksubwaySeoulstations = await KsubwayApi.fetchKsubwayStations(city: 'seoul');
_ksubwayStationsPreference.setSeoulstations(ksubwaySeoulstations);
ksubwaySeoulstations = await _ksubwayStationsPreference.getSeoulstations();
for (var i = 0; i < ksubwaySeoulstations.stationList!.length; i++) {
if (ksubwaySeoulstations.stationList![i].statnNm == null || ksubwaySeoulstations.stationList![i].statnNm == "null") continue;
seoulstations.add(ksubwaySeoulstations.stationList![i].statnNm);
}
}
@override
void initState() {
// TODO: implement initState
super.initState();
fetchKsubwayStations();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Column(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'지하철 검색에는',
style: textStyleTitle,
),
SizedBox(
height: 50,
child: Row(
children: [
const Text(
'K-SUBWAY',
style: textStyleTitle,
),
const SizedBox(width: 8),
AnimatedTextKit(
repeatForever: true,
animatedTexts: [
RotateAnimatedText('오픈소스', textStyle: textStyleTitle),
RotateAnimatedText('좋아 😘', textStyle: textStyleTitle),
],
),
],
),
),
],
),
SizedBox(height: 16),
TextField(
textAlign: TextAlign.center,
controller: _searchStationTextEditingController,
keyboardType: TextInputType.text,
onChanged: (v) async {
stationSuggestions.clear();
for (var i = 0; i < ksubwaySeoulstations.stationList!.length; i++) {
String expValue = '';
v.isEmpty ? expValue = '' : expValue = '?' + v;
RegExp exp = RegExp(r'()' + expValue);
if (exp.hasMatch(ksubwaySeoulstations.stationList![i].statnNm!) && v.isEmpty == false) {
stationSuggestions.add(ksubwaySeoulstations.stationList![i]);
}
}
setState(() {});
},
decoration: InputDecoration(
suffixIcon: IconButton(
icon: const Icon(
Icons.arrow_forward_ios,
),
onPressed: () {
if (_searchStationTextEditingController.text.isNotEmpty) {
Application.router.navigateTo(
context,
"/arrinfo/${_searchStationTextEditingController.text}",
transition: TransitionType.materialFullScreenDialog,
);
}
},
),
hintText: '입력해주세요',
hintStyle: textStyleSub1,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(100),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
),
),
filled: true,
contentPadding: const EdgeInsets.all(16),
),
),
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.all(16),
height: 200.0,
child: stationSuggestions.isEmpty
? Center(
child: Text(
'검색 내용 없음',
style: textStyleSub2.copyWith(color: Colors.black38),
))
: ListView.builder(
itemCount: stationSuggestions.length,
itemBuilder: ((context, index) {
return GestureDetector(
onTap: () => _searchStationTextEditingController.text = stationSuggestions[index].statnNm!,
child: Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Text(
'#${stationSuggestions[index].subwayId!.toString()}',
style: textStyleSub1,
textAlign: TextAlign.start,
),
const Spacer(),
Text(
stationSuggestions[index].statnNm!,
style: textStyleSub1,
textAlign: TextAlign.end,
),
],
),
),
);
}),
),
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(18)),
color: Colors.grey,
),
),
],
),
),
CupertinoButton(
child: const Text('실험 기능'),
onPressed: () {
Application.router.navigateTo(context, "/exp", transition: TransitionType.cupertino);
},
),
CupertinoButton(
child: const Text('설정'),
onPressed: () {
Application.router.navigateTo(context, "/setting", transition: TransitionType.cupertino);
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/screens/exp_screen.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ksubway/components/app_title.dart';
import 'package:flutter_ksubway/components/subway_info.dart';
import 'package:flutter_ksubway/components/subway_line_button.dart';
import 'package:flutter_ksubway/models/exp_ksubway_info.dart';
import 'package:flutter_ksubway/services/exp_ksubway_api.dart';
import 'package:flutter_ksubway/style/subwayStyles.dart';
class ExpScreen extends StatefulWidget {
const ExpScreen({Key? key}) : super(key: key);
@override
State<ExpScreen> createState() => _ExpScreenState();
}
class _ExpScreenState extends State<ExpScreen> with TickerProviderStateMixin {
final List<String> lineNumCd = <String>['1', '2', '3', '4', '5', '6', '7', '8', '9', 'SU', 'K', 'KK', 'G'];
final List<String> lineNumTitles = <String>['1 호선', '2 호선', '3 호선', '4 호선', '5 호선', '6 호선', '7 호선', '8 호선', '9 호선', '분당선', '경의중앙선', '경강선', '경춘선'];
late List<AnimationController> animationControllerList = [];
final subwayInfoScrollController = ScrollController();
final subwayLineScrollController = ScrollController();
int lineNumPageIndex = 0;
ExpksubwayApi expksubwayApi = ExpksubwayApi();
ExpksubwayInfo expksubwayInfo = ExpksubwayInfo();
List<TtcVOList> ttcVOList = [];
void fetchAll() async {
expksubwayInfo = await expksubwayApi.fetchExpksubwayInfo("1");
ttcVOList = expksubwayInfo.ttcVOList ?? [];
ttcVOList.sort(((a, b) => a.trainY!.compareTo(b.trainY!)));
setState(() {});
}
void updateExpksubwayInfo(String lineNumCd) async {
expksubwayInfo = await expksubwayApi.fetchExpksubwayInfo(lineNumCd);
ttcVOList = expksubwayInfo.ttcVOList ?? [];
ttcVOList.sort(((a, b) => a.trainY!.compareTo(b.trainY!)));
setState(() {});
}
@override
void initState() {
// TODO: implement initState
super.initState();
for (var i = 0; i < lineNumCd.length; i++) {
final _animationController = AnimationController(duration: const Duration(milliseconds: 250), lowerBound: 0.0, upperBound: .45, vsync: this);
_animationController.addListener(() {
setState(() {});
});
animationControllerList.add(_animationController);
}
fetchAll();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
const CupertinoNavigationBar(
previousPageTitle: 'back',
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
AppTitle(title: 'K - SUBWAY Fighter'),
],
),
),
const SizedBox(height: 8),
// -- content
Expanded(
child: Row(
children: [
SizedBox(
width: 100,
child: ListView.builder(
controller: subwayLineScrollController,
itemCount: lineNumCd.length,
itemBuilder: (BuildContext context, int index) {
void _onTapDown(TapDownDetails details) {
animationControllerList[index].forward();
}
void _onTapUp(TapUpDetails details) {
animationControllerList[index].reverse();
}
return GestureDetector(
onTap: () {
lineNumPageIndex = index;
updateExpksubwayInfo(lineNumCd[index]);
},
onTapDown: _onTapDown,
onTapUp: _onTapUp,
child: SubwayLineButton(
animationControllerList: animationControllerList,
lineNumTitles: lineNumTitles,
lineNumColors: lineNumColors,
index: index,
),
);
},
),
),
SubwayInfo(
subwayInfoScrollController: subwayInfoScrollController,
ttcVOList: ttcVOList,
lineNumColors: lineNumColors,
lineNumPageIndex: lineNumPageIndex,
),
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/screens/notfound_screen.dart | import 'package:flutter/material.dart';
class NotFoundScreen extends StatefulWidget {
const NotFoundScreen({Key? key}) : super(key: key);
@override
State<NotFoundScreen> createState() => _NotFoundScreenState();
}
class _NotFoundScreenState extends State<NotFoundScreen> {
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: Text('404 Page'),
),
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/screens/arrinfo_screen.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_countdown_timer/current_remaining_time.dart';
import 'package:flutter_countdown_timer/flutter_countdown_timer.dart';
import 'package:flutter_ksubway/main.dart';
import 'package:flutter_ksubway/models/ksubway_arrinfo.dart';
import 'package:flutter_ksubway/services/ksubway_api.dart';
import 'package:flutter_ksubway/style/textStyles.dart';
class ArrInfoScreen extends StatefulWidget {
final String stationName;
const ArrInfoScreen(this.stationName, {Key? key}) : super(key: key);
@override
State<ArrInfoScreen> createState() => _ArrInfoScreenState();
}
class _ArrInfoScreenState extends State<ArrInfoScreen> {
Timer? timer;
List<int> endTimes = [];
KsubwayArrinfo _ksubwayArrinfo = KsubwayArrinfo();
List<RealtimeArrivalList> realtimeArrivalList = [];
List<int> createEndTimes(List<RealtimeArrivalList> realtimeArrivalList) {
List<int> _result = [];
for (var i = 0; i < realtimeArrivalList.length; i++) {
DateTime _now = DateTime.now();
DateTime _serverNow = DateTime.parse(realtimeArrivalList[i].recptnDt ?? _now.toString());
int _gap = (_now.second - _serverNow.second).abs();
int _endTime = _now.millisecondsSinceEpoch + Duration(seconds: int.parse(realtimeArrivalList[i].barvlDt ?? "0") - _gap).inMilliseconds;
_result.add(_endTime);
}
return _result;
}
void fetchAll() async {
_ksubwayArrinfo = await KsubwayApi.fetchKsubwayArrinfo(
startPage: "0",
endPage: "50",
realtimeType: "realtimeStationArrival",
stationName: widget.stationName,
);
realtimeArrivalList = _ksubwayArrinfo.realtimeArrivalList ?? [];
endTimes = createEndTimes(realtimeArrivalList);
setState(() {});
}
@override
void initState() {
// TODO: implement initState
super.initState();
timer = Timer.periodic(const Duration(seconds: 15), (Timer t) => fetchAll());
fetchAll();
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.stationName, style: textStyleTitle),
centerTitle: true,
),
body: SafeArea(
child: Column(
children: [
const SizedBox(height: 16),
Expanded(
child: Row(
children: [
Expanded(
child: ListView.builder(
itemCount: realtimeArrivalList.length,
itemBuilder: (context, index) {
return SubwayCard(realtimeArrivalList: realtimeArrivalList, endTimes: endTimes, widget: widget, index: index);
},
),
),
],
),
),
],
),
),
);
}
}
class SubwayCard extends StatelessWidget {
const SubwayCard({
Key? key,
required this.realtimeArrivalList,
required this.endTimes,
required this.widget,
required this.index,
}) : super(key: key);
final List<RealtimeArrivalList> realtimeArrivalList;
final List<int> endTimes;
final ArrInfoScreen widget;
final int index;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Column(
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 32.0),
child: Center(
child: Text(
realtimeArrivalList[index].trainLineNm!.replaceAll(' (급행)', ''),
style: textStyleSub1,
textAlign: TextAlign.center,
),
),
// color: Colors.white.withAlpha(100),
decoration: BoxDecoration(
borderRadius: const BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)),
color: MyApp.themeNotifier.value == ThemeMode.light ? Colors.white : Color(0xff454545),
boxShadow: [
BoxShadow(
color: MyApp.themeNotifier.value == ThemeMode.light ? Color.fromARGB(255, 129, 129, 129) : Color.fromARGB(255, 22, 22, 22),
offset: const Offset(2.0, 2.0),
blurRadius: 4.0,
),
],
),
),
AnimatedContainer(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Row(
children: [
Column(
children: [
Container(
width: 90, // 장평이 안맞아서 가로 길이 고정
child: Center(
child: Text(
realtimeArrivalList[index].subwayId!,
style: textStyleSub1,
textAlign: TextAlign.center,
),
),
color: Color.fromARGB(255, 129, 112, 112),
),
Container(
width: 90, // 장평이 안맞아서 가로 길이 고정
child: Center(
child: Text(
realtimeArrivalList[index].btrainSttus! == "null" ? "일반" : realtimeArrivalList[index].btrainSttus!,
style: textStyleSub1,
textAlign: TextAlign.center,
),
),
color: Color.fromARGB(255, 94, 34, 34).withAlpha(100),
),
],
),
Container(height: 50, width: 1, color: Colors.grey),
const SizedBox(
width: 8,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
"종착역 : ${realtimeArrivalList[index].bstatnNm!.replaceAll(' (급행)', '')}",
style: textStyleSub1,
),
],
),
),
Expanded(
child: CountdownTimer(
endTime: endTimes[index],
widgetBuilder: (_, CurrentRemainingTime? time) {
if (time == null) {
return Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Text(
'${widget.stationName} ${parseArrCode(realtimeArrivalList[index].arvlCd!)}',
style: textStyleSub1.copyWith(color: Colors.redAccent),
textAlign: TextAlign.right,
),
);
}
return Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'${widget.stationName} ${parseArrCode(realtimeArrivalList[index].arvlCd!)}',
style: textStyleSub1.copyWith(color: Colors.redAccent),
textAlign: TextAlign.right,
),
Text(
parseTime(time.min, time.sec),
style: textStyleSub1.copyWith(color: Colors.redAccent),
textAlign: TextAlign.right,
),
],
),
);
},
),
),
],
),
duration: const Duration(milliseconds: 220),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(8)),
color: MyApp.themeNotifier.value == ThemeMode.light ? Colors.white : Color(0xff454545),
boxShadow: [
BoxShadow(
color: MyApp.themeNotifier.value == ThemeMode.light ? Color.fromARGB(255, 129, 129, 129) : Color.fromARGB(255, 22, 22, 22),
offset: const Offset(2.0, 2.0),
blurRadius: 4.0,
),
],
),
),
],
),
);
}
}
String parseTime(int? min, int? sec) {
int _min = min ?? 0;
int _sec = sec ?? 0;
if (_min == 0) return "$_sec초";
if (_min == 0 && _sec == 0) return "";
return "$_min분 $_sec초";
}
String parseArrCode(String code) {
switch (code) {
case '0':
return '진입';
case '1':
return '도착';
case '2':
return '출발';
case '3':
return '전역출발';
case '4':
return '전역진입';
case '5':
return '전역도착';
case '99':
return '도착 전';
default:
return code;
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/screens/setting_screen.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ksubway/main.dart';
import 'package:flutter_ksubway/models/ksubway_seoulstations.dart';
import 'package:flutter_ksubway/preferences/exp_api_preference.dart';
import 'package:flutter_ksubway/preferences/ksubway_stations_preference.dart';
import 'package:flutter_ksubway/preferences/theme_preference.dart';
import 'package:flutter_ksubway/services/ksubway_api.dart';
import 'package:flutter_ksubway/style/textStyles.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
class SettingScreen extends StatefulWidget {
const SettingScreen({Key? key}) : super(key: key);
@override
State<SettingScreen> createState() => _SettingScreenState();
}
class _SettingScreenState extends State<SettingScreen> {
KsubwaySeoulstations ksubwaySeoulstations = KsubwaySeoulstations(stationList: []);
final KsubwayStationsPreference _ksubwayStationsPreference = KsubwayStationsPreference();
final expApiEndpointTextEditingController = TextEditingController();
final expApiPreference = ExpApiPreference();
final themePreference = ThemePreference();
String expApiEndpoint = "";
Future<void> _launchInBrowser(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.externalApplication,
)) {
throw 'Could not launch $url';
}
}
void fetchKsubwayStations() async {
ksubwaySeoulstations = await KsubwayApi.fetchKsubwayStations(city: 'seoul');
_ksubwayStationsPreference.setSeoulstations(ksubwaySeoulstations);
}
void restoreSettings() async {
expApiEndpoint = await expApiPreference.getApiEndpoint();
setState(() {});
}
@override
void initState() {
// TODO: implement initState
super.initState();
fetchKsubwayStations();
restoreSettings();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
const CupertinoNavigationBar(
previousPageTitle: "back",
),
Form(
autovalidateMode: AutovalidateMode.always,
onChanged: () {
Form.of(primaryFocus!.context!)?.save();
},
child: CupertinoFormSection.insetGrouped(
header: const Text(
'Experimental Section',
style: textStyleSub2,
),
children: List<Widget>.generate(1, (int index) {
return CupertinoTextFormFieldRow(
controller: expApiEndpointTextEditingController..text = expApiEndpoint,
prefix: const Text(
'API Endpoint',
style: textStyleTextFormFieldTitle,
),
placeholder: 'Enter text',
placeholderStyle: textStyleTextFormFieldContent,
validator: (String? value) {
if (value == null || value.isEmpty) {
return 'Please enter a value';
}
if (!Uri.parse(value).isAbsolute) return 'Please enter valid api endpoint';
},
onSaved: (value) {
expApiPreference.setApiEndpoint(value ?? "");
},
onEditingComplete: () => expApiEndpointTextEditingController.clear(),
);
}),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'서울 역정보 업데이트',
style: textStyleSub1,
),
CupertinoButton(
child: const FaIcon(FontAwesomeIcons.arrowsRotate),
onPressed: () => fetchKsubwayStations(),
)
],
),
Center(
child: IconButton(
padding: EdgeInsets.zero,
onPressed: () async {
setState(() {});
themePreference.setDarkTheme(MyApp.themeNotifier.value == ThemeMode.light);
MyApp.themeNotifier.value = MyApp.themeNotifier.value == ThemeMode.light ? ThemeMode.dark : ThemeMode.light;
},
icon: Icon(MyApp.themeNotifier.value == ThemeMode.light ? Icons.dark_mode : Icons.light_mode),
),
),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 8),
child: Divider(thickness: 0.2, color: Colors.grey),
),
const Spacer(),
Container(
margin: const EdgeInsets.only(bottom: 32),
height: 120,
child: Column(
children: [
IconButton(
padding: EdgeInsets.zero,
onPressed: () {
_launchInBrowser(Uri(
scheme: 'https',
host: 'github.com',
path: '/dart-bird/flutter_ksubway',
));
},
icon: const FaIcon(FontAwesomeIcons.github),
),
const Text(
'Created by dart-bird',
style: textStyleFooter,
),
const SizedBox(height: 5),
OutlinedButton(
onPressed: () {
showLicensePage(context: context);
},
child: const Text("License", style: textStyleFooter),
),
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/style/subwayStyles.dart | import 'package:flutter/material.dart';
final List<Color> lineNumColors = <Color>[
const Color.fromARGB(255, 29, 93, 212),
const Color(0xff3B9F37),
const Color(0xffff8439),
const Color(0xff4193f8),
const Color(0xffb15ed9),
const Color(0xffdc7732),
const Color(0xff9bb556),
const Color(0xffff2580),
const Color(0xffebb700),
const Color(0xffffe32a),
const Color(0xff99ffd5),
const Color(0xff1279ff),
const Color(0xff2d9b76),
];
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/style/textStyles.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
const textStyleTextFormFieldTitle = TextStyle(
fontFamily: 'GimpoGothic',
fontWeight: FontWeight.normal,
// fontSize: 15,
);
const textStyleTextFormFieldContent = const TextStyle(
fontFamily: 'GimpoGothic',
fontWeight: FontWeight.normal,
color: CupertinoColors.placeholderText,
);
const textStyleTitle = TextStyle(
fontFamily: 'GimpoGothic',
fontWeight: FontWeight.bold,
fontSize: 25,
);
const textStyleSub1 = TextStyle(
fontFamily: 'GimpoGothic',
fontWeight: FontWeight.normal,
fontSize: 15,
);
const textStyleSub2 = TextStyle(
fontFamily: 'GimpoGothic',
fontWeight: FontWeight.normal,
fontSize: 12,
);
const textStyleFooter = TextStyle(
fontFamily: 'GimpoGothic',
fontWeight: FontWeight.normal,
fontSize: 12,
color: Colors.grey,
);
| 0 |
mirrored_repositories/flutter_ksubway/lib | mirrored_repositories/flutter_ksubway/lib/style/theme_styles.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
ThemeData darkTheme = ThemeData.dark().copyWith(
iconTheme: const IconThemeData(color: Colors.white),
cupertinoOverrideTheme: const CupertinoThemeData(
brightness: Brightness.dark,
primaryColor: CupertinoColors.systemBlue,
textTheme: CupertinoTextThemeData(),
barBackgroundColor: CupertinoColors.systemBackground,
),
);
ThemeData lightTheme = ThemeData.light().copyWith(
scaffoldBackgroundColor: const Color.fromARGB(255, 243, 243, 243),
iconTheme: const IconThemeData(color: Colors.black),
appBarTheme: const AppBarTheme(
iconTheme: IconThemeData(
color: Colors.black87,
),
backgroundColor: Colors.white,
titleTextStyle: TextStyle(color: Colors.black87),
),
);
| 0 |
mirrored_repositories/flutter_ksubway | mirrored_repositories/flutter_ksubway/test/widget_test.dart | // 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:flutter_ksubway/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const 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);
});
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/remote_control.dart | import 'dart:async';
import 'dart:convert';
import 'dart:math' as math;
import 'dart:ui';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:http/http.dart' as http;
import 'package:just_throttle_it/just_throttle_it.dart';
import 'package:network_info_plus/network_info_plus.dart';
import 'package:network_tools/network_tools.dart';
// import 'package:ping_discover_network/ping_discover_network.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:transparent_image/transparent_image.dart';
import 'package:xml/xml.dart' as xml;
import 'equalizer_screen.dart';
import 'models.dart';
import 'open_media.dart';
import 'settings_screen.dart';
import 'utils.dart';
import 'vlc_configuration_guide.dart';
import 'widgets.dart';
var _headerFooterBgColor = const Color.fromRGBO(241, 241, 241, 1.0);
const _tickIntervalSeconds = 1;
const _sliderThrottleMilliseconds = 333;
enum _PopupMenuChoice {
audioTrack,
emptyPlaylist,
fullscreen,
playbackSpeed,
settings,
snapshot,
subtitleTrack
}
class RemoteControl extends StatefulWidget {
final SharedPreferences prefs;
final Settings settings;
const RemoteControl({
Key? key,
required this.prefs,
required this.settings,
}) : super(key: key);
@override
State<StatefulWidget> createState() => _RemoteControlState();
}
class _RemoteControlState extends State<RemoteControl> {
//#region Setup state
bool _autoConnecting = false;
String? _autoConnectError;
String? _autoConnectHost;
//#endregion
//#region HTTP requests / timer state
final http.Client _client = http.Client();
int? _lastStatusResponseCode;
int? _lastPlaylistResponseCode;
String? _lastPlaylistResponseBody;
/// Timer which controls polling status and playlist info from VLC.
late Timer _pollingTicker =
Timer.periodic(const Duration(seconds: _tickIntervalSeconds), _tick);
/// Timer used for single updates when polling is disabled.
Timer? _singleUpdateTimer;
//#endregion
//#region VLC status state
/// Contains subtitle and audio track information for use in the menu.
VlcStatusResponse? _lastStatusResponse;
/// Used to send equalizer changes to EqualizerScreen when it's open.
final StreamController<Equalizer?> _equalizerController =
StreamController<Equalizer?>.broadcast();
// Fields populated from the latest VLC status response
String _state = 'stopped';
String _title = '';
String _artist = '';
Duration _time = Duration.zero;
Duration _length = Duration.zero;
int _volume = 256;
double _rate = 1.0;
bool _repeat = false;
bool _loop = false;
bool _random = false;
Equalizer? _equalizer;
/// Used to ignore status in any in-flight requests after we've told VLC to
/// toggle playback settings.
DateTime? _ignoreLoopStatusBefore;
DateTime? _ignoreRandomStatusBefore;
DateTime? _ignoreRateStatusBefore;
//#endregion
//#region Playlist state
final ScrollController _scrollController = ScrollController();
List<PlaylistItem> _playlist = [];
PlaylistItem? _playing;
String? _backgroundArtUrl;
bool _reusingBackgroundArt = false;
bool _showAddMediaButton = true;
//#endregion
//#region Volume state
/// Controls sliding the volume controls in and out.
bool _showVolumeControls = false;
/// Set to true while volume controls are animating.
bool _animatingVolumeControls = false;
/// Set to true when the user is dragging the volume slider - used to ignore
/// volume in status updates from VLC.
bool _draggingVolume = false;
/// Used to ignore volume status in any in-flight requests after we've told
/// VLC to change the volume.
DateTime? _ignoreVolumeStatusBefore;
/// Previous volume when the volume button was long-pressed to mute.
int? _preMuteVolume;
/// Timer used for automatically hiding the volume controls after a delay.
Timer? _hideVolumeControlsTimer;
//#endregion
//#region Time state
/// Toggles between showing length and time left in the track timing section.
bool _showTimeLeft = false;
/// Set to true when the user is dragging the time slider - used to ignore
/// time in status updates from VLC.
bool _draggingTime = false;
/// Set to true when the user is dragging the playback speed slider - used to
/// ignore rate in status updates from VLC.
bool _draggingRate = false;
//#endregion
@override
initState() {
super.initState();
_scrollController.addListener(_handleScroll);
_checkWifi();
}
@override
dispose() {
if (_pollingTicker.isActive) {
_pollingTicker.cancel();
}
super.dispose();
}
//#region Connectivity
_checkWifi() async {
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult != ConnectivityResult.wifi) {
if (mounted) {
_showWifiAlert(context);
}
}
}
_showWifiAlert(BuildContext context) async {
var subscription = Connectivity().onConnectivityChanged.listen((result) {
if (result == ConnectivityResult.wifi) {
Navigator.pop(context);
}
});
await showDialog(
context: context,
builder: (context) => const AlertDialog(
title: Text('Turn on Wi-Fi'),
content: Text(
'A Wi-Fi connection was not detected.\n\nRemote Control for VLC needs to connect to your local network to control VLC.',
),
),
);
subscription.cancel();
}
//#endregion
//#region HTTP requests
get _authHeaders => {
'Authorization':
'Basic ${base64Encode(utf8.encode(':${widget.settings.connection.password}'))}'
};
String _artUrlForPlid(String plid) =>
'http://${widget.settings.connection.authority}/art?item=$plid';
/// Send a request to the named VLC API [endpoint] with any [queryParameters]
/// given and return parsed response XML if successful.
///
/// For the playlist endpoint, the response will be ignored if it's exactly
/// the same as the last playlist response we received.
Future<xml.XmlDocument?> _serverRequest(String endpoint,
[Map<String, String>? queryParameters]) async {
http.Response response;
try {
response = await _client
.get(
Uri.http(
widget.settings.connection.authority,
'/requests/$endpoint.xml',
queryParameters,
),
headers: _authHeaders,
)
.timeout(const Duration(seconds: 1));
} catch (e) {
assert(() {
if (e is! TimeoutException) {
print('_serverRequest error: $e');
}
return true;
}());
_resetPlaylist();
setState(() {
if (endpoint == 'status') {
_lastStatusResponseCode = -1;
} else if (endpoint == 'playlist') {
_lastPlaylistResponseCode = -1;
_lastPlaylistResponseBody = null;
}
});
return null;
}
setState(() {
if (endpoint == 'status') {
_lastStatusResponseCode = response.statusCode;
} else if (endpoint == 'playlist') {
_lastPlaylistResponseCode = response.statusCode;
}
});
if (response.statusCode != 200) {
if (endpoint == 'playlist') {
_lastPlaylistResponseBody = null;
}
return null;
}
var responseBody = utf8.decode(response.bodyBytes);
if (endpoint == 'playlist') {
if (responseBody == _lastPlaylistResponseBody) {
return null;
}
_lastPlaylistResponseBody = responseBody;
}
return xml.XmlDocument.parse(responseBody);
}
Future<Equalizer?> _equalizerRequest(
Map<String, String> queryParameters) async {
xml.XmlDocument? document = await _serverRequest('status', queryParameters);
if (document == null) {
return null;
}
var equalizer = VlcStatusResponse(document).equalizer;
assert(() {
//print('$queryParameters => $equalizer');
return true;
}());
return equalizer;
}
/// Send a request to VLC's status API endpoint - this is used to submit
/// commands as well as getting the current state of VLC.
_statusRequest([Map<String, String>? queryParameters]) async {
var requestTime = DateTime.now();
xml.XmlDocument? document = await _serverRequest('status', queryParameters);
if (document == null) {
_equalizerController.add(null);
return;
}
var statusResponse = VlcStatusResponse(document);
assert(() {
if (queryParameters != null) {
//print('VlcStatusRequest(${queryParameters ?? {}}) => $statusResponse');
}
return true;
}());
// State changes aren't reflected in commands which start and stop playback
var ignoreStateUpdates = queryParameters != null &&
(queryParameters['command'] == 'pl_play' ||
queryParameters['command'] == 'pl_pause' ||
queryParameters['command'] == 'pl_stop');
// Volume changes aren't reflected in 'volume' command responses
var ignoreVolumeUpdates = _draggingVolume ||
queryParameters != null && queryParameters['command'] == 'volume' ||
_ignoreVolumeStatusBefore != null &&
requestTime.isBefore(_ignoreVolumeStatusBefore!);
var ignoreRateUpdate = _draggingRate ||
_ignoreRateStatusBefore != null &&
requestTime.isBefore(_ignoreRateStatusBefore!);
setState(() {
if (!ignoreStateUpdates) {
_state = statusResponse.state;
}
_length = statusResponse.length.isNegative
? Duration.zero
: statusResponse.length;
if (!ignoreVolumeUpdates) {
_volume = statusResponse.volume.clamp(0, 512);
}
if (!ignoreRateUpdate) {
_rate = statusResponse.rate;
}
// Keep the current title and artist when playback is stopped
if (statusResponse.currentPlId != '-1') {
_title = statusResponse.title;
_artist = statusResponse.artist;
}
if (!_draggingTime) {
var responseTime = statusResponse.time;
// VLC will let time go over and under length using relative seek times
// and will send the out-of-range time back to you before it corrects
// itself.
if (responseTime.isNegative) {
_time = Duration.zero;
} else if (responseTime > _length) {
_time = _length;
} else {
_time = responseTime;
}
}
// Set the background art URL when the current playlist item changes.
// Keep the current URL when playback is stopped.
if (statusResponse.currentPlId != '-1' &&
statusResponse.currentPlId != _lastStatusResponse?.currentPlId) {
// Keep using the existing URL if the new item has artwork and both
// items are using the same artwork file.
_reusingBackgroundArt = _backgroundArtUrl != null &&
statusResponse.artworkUrl.isNotEmpty &&
statusResponse.artworkUrl == _lastStatusResponse?.artworkUrl;
if (statusResponse.artworkUrl.isNotEmpty && !_reusingBackgroundArt) {
_backgroundArtUrl = _artUrlForPlid(statusResponse.currentPlId);
} else if (statusResponse.artworkUrl.isEmpty) {
_backgroundArtUrl = null;
}
}
if (_ignoreLoopStatusBefore == null ||
requestTime.isAfter(_ignoreLoopStatusBefore!)) {
_loop = statusResponse.loop;
_repeat = statusResponse.repeat;
}
if (_ignoreRandomStatusBefore == null ||
requestTime.isAfter(_ignoreRandomStatusBefore!)) {
_random = statusResponse.random;
}
_equalizer = statusResponse.equalizer;
_equalizerController.add(_equalizer);
_lastStatusResponse = statusResponse;
});
}
/// Sends a request to VLC's playlist API endpoint to get the current playlist
/// (which also indicates the currently playing item).
_playlistRequest() async {
xml.XmlDocument? document = await _serverRequest('playlist', null);
if (document == null) {
return;
}
var playlistResponse = VlcPlaylistResponse.fromXmlDocument(document);
setState(() {
// Clear current title and background URL if the playlist is cleared
if (_playlist.isNotEmpty && playlistResponse.items.isEmpty) {
_title = '';
_backgroundArtUrl = '';
_reusingBackgroundArt = false;
}
if (playlistResponse.items.length < _playlist.length) {
SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
_showAddMediaButtonIfNotScrollable();
});
}
_playlist = playlistResponse.items;
_playing = playlistResponse.currentItem;
});
}
_updateStatusAndPlaylist() {
if (!widget.settings.connection.hasIp) {
_resetPlaylist();
return;
}
_statusRequest();
_playlistRequest();
}
/// Send a command with no arguments to VLC.
///
/// If polling is disabled, also schedules an update to get the next status.
_statusCommand(String command) {
_statusRequest({'command': command});
_scheduleSingleUpdate();
}
//#endregion
//#region Polling and timers
_tick(timer) async {
_updateStatusAndPlaylist();
}
_togglePolling(context) {
String message;
if (_pollingTicker.isActive) {
_pollingTicker.cancel();
message = 'Paused polling for status updates';
} else {
_pollingTicker =
Timer.periodic(const Duration(seconds: _tickIntervalSeconds), _tick);
message = 'Resumed polling for status updates';
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
));
setState(() {});
}
_scheduleSingleUpdate() async {
// Ticker will do the UI updates, no need to schedule any further update
if (_pollingTicker.isActive) {
return;
}
// Cancel any existing delay timer so the latest state is updated in one shot
if (_singleUpdateTimer != null && _singleUpdateTimer!.isActive) {
_singleUpdateTimer!.cancel();
}
_singleUpdateTimer = Timer(const Duration(seconds: _tickIntervalSeconds),
_updateStatusAndPlaylist);
}
//#endregion
//#region Setup
_showConfigurationGuide() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const VlcConfigurationGuide(),
),
);
}
_autoConnect() async {
setState(() {
_autoConnecting = true;
_autoConnectError = null;
_autoConnectHost = null;
});
if (await Connectivity().checkConnectivity() != ConnectivityResult.wifi) {
setState(() {
_autoConnecting = false;
_autoConnectError = 'Not connected to Wi-Fi';
});
return;
}
var ip = await NetworkInfo().getWifiIP();
if (ip == null) {
setState(() {
_autoConnecting = false;
_autoConnectError = 'Unable to get Wi-Fi IP address';
});
return;
}
var subnet = ip.substring(0, ip.lastIndexOf('.'));
final stream = HostScanner.discoverPort(subnet, int.parse(defaultPort),
timeout: const Duration(seconds: 1));
List<String> ips = [];
stream.listen((OpenPort port) {
if (port.isOpen) {
ips.add(port.ip);
}
}, onDone: () {
if (ips.isEmpty) {
setState(() {
_autoConnecting = false;
_autoConnectError =
'Couldn\'t find any hosts running port 8080 on subnet $subnet';
});
return;
}
setState(() {
if (ips.isNotEmpty) {
_autoConnectHost =
'Found multiple hosts, using the first one: ${ips.join(', ')}';
}
_autoConnectHost = 'Found host: ${ips.first}';
});
_testConnection(ips.first);
}, onError: (error) {
setState(() {
_autoConnecting = false;
_autoConnectError = 'Error scanning network: $error';
});
}, cancelOnError: true);
}
_testConnection(String ip) async {
http.Response response;
try {
response = await http.get(
Uri.http(
'$ip:$defaultPort',
'/requests/status.xml',
),
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(':$defaultPassword'))}'
}).timeout(const Duration(seconds: 1));
} catch (e) {
setState(() {
_autoConnecting = false;
if (e is TimeoutException) {
_autoConnectError = 'Connection timed out';
} else {
_autoConnectError = 'Connection error: ${e.runtimeType}';
}
});
return;
}
if (response.statusCode != 200) {
setState(() {
_autoConnecting = false;
if (response.statusCode == 401) {
_autoConnectError =
'Default password was invalid – configure the connection manually.';
} else {
_autoConnectError =
'Unexpected response: status code: ${response.statusCode}';
}
});
return;
}
widget.settings.connection.ip = ip;
widget.settings.connection.port = defaultPort;
widget.settings.connection.password = defaultPassword;
widget.settings.save();
setState(() {
_autoConnecting = false;
});
}
_showSettings() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SettingsScreen(
settings: widget.settings,
onSettingsChanged: () {
setState(() {
widget.settings.save();
});
},
),
),
);
}
//#endregion
//#region Playlist
_resetPlaylist() {
_playing = null;
_backgroundArtUrl = null;
_reusingBackgroundArt = false;
_playlist = [];
_title = '';
_showAddMediaButton = true;
}
_deletePlaylistItem(PlaylistItem item) {
showDialog(
context: context,
builder: (BuildContext context) => AlertDialog(
title: const Text('Remove item from playlist?'),
content: Text(item.title),
actions: <Widget>[
TextButton(
child: const Text("CANCEL"),
onPressed: () {
Navigator.pop(context);
},
),
TextButton(
child: const Text("REMOVE"),
onPressed: () {
_statusRequest({
'command': 'pl_delete',
'id': item.id,
});
_scheduleSingleUpdate();
Navigator.pop(context);
},
)
],
),
);
}
//#endregion
//#region Popup menu
_onPopupMenuChoice(_PopupMenuChoice choice) {
switch (choice) {
case _PopupMenuChoice.audioTrack:
_chooseAudioTrack();
break;
case _PopupMenuChoice.emptyPlaylist:
_emptyPlaylist();
break;
case _PopupMenuChoice.fullscreen:
_toggleFullScreen();
break;
case _PopupMenuChoice.playbackSpeed:
_showPlaybackSpeedControl();
break;
case _PopupMenuChoice.settings:
_showSettings();
break;
case _PopupMenuChoice.snapshot:
_takeSnapshot();
break;
case _PopupMenuChoice.subtitleTrack:
_chooseSubtitleTrack();
break;
}
}
Future<LanguageTrack?> _chooseLanguageTrack(List<LanguageTrack> options,
{bool allowNone = false}) {
var dialogOptions = options
.map((option) => SimpleDialogOption(
onPressed: () {
Navigator.pop(context, option);
},
child: Text(option.name),
))
.toList();
if (allowNone) {
dialogOptions.insert(
0,
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, LanguageTrack('(None)', -1));
},
child: const Text('(None)'),
));
}
return showDialog<LanguageTrack>(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
children: dialogOptions,
);
},
);
}
_chooseSubtitleTrack() async {
if (_lastStatusResponse == null) {
return;
}
LanguageTrack? subtitleTrack = await _chooseLanguageTrack(
_lastStatusResponse!.subtitleTracks,
allowNone: true);
if (subtitleTrack != null) {
_statusRequest({
'command': 'subtitle_track',
'val': subtitleTrack.streamNumber.toString(),
});
}
}
_chooseAudioTrack() async {
if (_lastStatusResponse == null) {
return;
}
LanguageTrack? audioTrack =
await _chooseLanguageTrack(_lastStatusResponse!.audioTracks);
if (audioTrack != null) {
_statusRequest({
'command': 'audio_track',
'val': audioTrack.streamNumber.toString(),
});
}
}
_toggleEqualizer() {
_statusRequest({
'command': 'enableeq',
'val': _equalizer?.enabled == true ? '0' : '1'
});
_scheduleSingleUpdate();
}
_showEqualizer() {
if (_equalizer == null) {
return;
}
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EqualizerScreen(
equalizer: _equalizer!,
equalizerStream: _equalizerController.stream,
onToggleEnabled: (enabled) {
return _equalizerRequest(
{'command': 'enableeq', 'val': enabled ? '1' : '0'});
},
onPresetChange: (presetId) {
return _equalizerRequest(
{'command': 'setpreset', 'val': '$presetId'});
},
onPreampChange: (value) {
return _equalizerRequest({'command': 'preamp', 'val': value});
},
onBandChange: (bandId, value) {
return _equalizerRequest(
{'command': 'equalizer', 'band': '$bandId', 'val': value});
},
),
),
);
}
_toggleFullScreen() {
_statusCommand('fullscreen');
}
_emptyPlaylist() {
_statusCommand('pl_empty');
}
_takeSnapshot() {
_statusCommand('snapshot');
}
/// Convert the VLC playback [_rate] to a slider value between 0.0 and 1.0,
/// where 0.25x → 0.0, 1.0x → 0.5 and 4.0x → 1.0.
///
/// This matches the range of VLC's own playback rate slider, but it's
/// possible for the rate to be set outside this range.
double get _rateSliderValue {
double value;
if (_rate == 1.0) {
value = 0.5;
} else if (_rate < 1) {
value = (_rate - 0.25) / 0.75 / 2;
} else {
value = 0.5 + ((_rate - 1) / 3.0 / 2);
}
return value.clamp(0.0, 1.0);
}
/// Convert a playback speed slider value between 0.0 and 1.0 to a VLC
/// playback [_rate], where 0.0 → 0.25x, 0.5 -> 1.0x and 1.0 → 4.0x.
///
/// This matches the range of VLC's own playback rate slider.
double _sliderValueToRate(double value) {
double rate;
if (value == 0.5) {
rate = 1.0;
} else if (value < 0.5) {
rate = 0.25 + (0.75 * value * 2);
} else {
rate = 1.0 + (3.0 * (value - 0.5) * 2);
}
return rate.clamp(0.25, 4.0);
}
_decrementRate(setState) {
setState(() {
_rate = math.max(0.25, ((_rate - 0.1) * 10.0).roundToDouble() / 10.0);
_setRate(_rate);
});
}
_incrementRate(setState) {
setState(() {
_rate = math.min(4.0, ((_rate + 0.1) * 10.0).roundToDouble() / 10.0);
_setRate(_rate);
});
}
_showPlaybackSpeedControl() {
var theme = Theme.of(context);
showModalBottomSheet(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
),
),
backgroundColor: Colors.white,
isScrollControlled: true,
context: context,
builder: (builder) {
return StatefulBuilder(
builder: (context, setState) {
return Wrap(
children: [
Padding(
padding: const EdgeInsets.only(left: 16, top: 12, bottom: 8),
child: Text(
'Playback speed',
style: TextStyle(
color: theme.primaryColor,
fontSize: 20,
),
),
),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 16.0, right: 8.0),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
const Text('0.25'),
Text(
'${_rate.toStringAsFixed(2)}x',
style: TextStyle(
color: theme.primaryColor,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const Text('4.00')
],
),
SliderTheme(
data: SliderTheme.of(context).copyWith(
trackShape: FullWidthTrackShape(),
),
child: Slider(
value: _rateSliderValue,
onChangeStart: (value) {
setState(() {
_draggingRate = true;
});
},
onChanged: (value) {
setState(() {
_rate = _sliderValueToRate(value);
});
Throttle.milliseconds(
_sliderThrottleMilliseconds,
_setRate,
[_rate]);
},
onChangeEnd: (value) {
_setRate(_rate);
setState(() {
_draggingRate = false;
});
},
),
),
],
),
),
),
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
right: 8, bottom: 4, left: 8),
child: ClipOval(
child: Material(
color: Colors.grey.shade200,
child: IconButton(
color: Colors.black,
icon: const Icon(Icons.keyboard_arrow_up),
onPressed: _rate < 4.0
? () {
_incrementRate(setState);
}
: null,
),
),
),
),
Padding(
padding: const EdgeInsets.only(
right: 8, top: 4, left: 8, bottom: 8),
child: ClipOval(
child: Material(
color: Colors.grey.shade200,
child: IconButton(
color: Colors.black,
icon: const Icon(Icons.keyboard_arrow_down),
onPressed: _rate > 0.25
? () {
_decrementRate(setState);
}
: null,
),
),
),
),
],
)
],
)
],
);
},
);
},
);
}
//#endregion
//#region Playlist
bool get _showFab =>
_lastStatusResponseCode == 200 &&
_showAddMediaButton &&
!_showVolumeControls &&
!_animatingVolumeControls;
/// Ensures the add media button is displayed if it's currently hidden and the
/// playlist contents become non-scrollable.
_showAddMediaButtonIfNotScrollable() {
if (!_showAddMediaButton &&
_scrollController.position.maxScrollExtent == 0.0) {
setState(() {
_showAddMediaButton = true;
});
}
}
/// Hides the add media button when scrolling down and re-displays it when
/// scrolling back up again.
_handleScroll() {
switch (_scrollController.position.userScrollDirection) {
case ScrollDirection.forward:
if (_scrollController.position.maxScrollExtent !=
_scrollController.position.minScrollExtent) {
setState(() {
_showAddMediaButton = true;
});
}
break;
case ScrollDirection.reverse:
if (_scrollController.position.maxScrollExtent !=
_scrollController.position.minScrollExtent) {
setState(() {
_showAddMediaButton = false;
});
}
break;
case ScrollDirection.idle:
break;
}
}
//#endregion
//#region Volume control/slider
double get _volumeSliderValue => _volume / volumeSliderScaleFactor;
int _scaleVolumePercent(double percent) =>
(percent * volumeSliderScaleFactor).round();
_setVolumePercent(double percent, {bool finished = true}) {
_ignoreVolumeStatusBefore = DateTime.now();
// Preempt the expected volume
setState(() {
_volume = _scaleVolumePercent(percent);
});
_statusRequest({
'command': 'volume',
'val': '${_scaleVolumePercent(percent)}',
});
if (finished) {
_scheduleSingleUpdate();
}
}
_setVolumeRelative(int relativeValue) {
// Nothing to do if already min or max
if ((_volume <= 0 && relativeValue < 0) ||
(_volume >= 512 && relativeValue > 0)) return;
_ignoreVolumeStatusBefore = DateTime.now();
// Preempt the expected volume
setState(() {
_volume = (_volume + relativeValue).clamp(0, 512);
if (_volume == 0) {
_preMuteVolume = null;
}
});
_statusRequest({
'command': 'volume',
'val': '${relativeValue > 0 ? '+' : ''}$relativeValue',
});
_scheduleSingleUpdate();
}
_toggleVolumeControls([bool? show]) {
show ??= !_showVolumeControls;
setState(() {
_showVolumeControls = show!;
_animatingVolumeControls = true;
});
if (show == true) {
_scheduleHidingVolumeControls();
} else {
_cancelHidingVolumeControls();
}
}
_toggleMute() {
if (_volume > 0) {
_preMuteVolume = _volume;
_setVolumePercent(0);
} else {
_setVolumePercent(_preMuteVolume != null
? _preMuteVolume! / volumeSliderScaleFactor
: 100);
}
if (_showVolumeControls) {
_scheduleHidingVolumeControls(2);
}
}
_cancelHidingVolumeControls() {
if (_hideVolumeControlsTimer != null &&
_hideVolumeControlsTimer!.isActive) {
_hideVolumeControlsTimer!.cancel();
_hideVolumeControlsTimer = null;
}
}
_scheduleHidingVolumeControls([int seconds = 4]) {
_cancelHidingVolumeControls();
_hideVolumeControlsTimer =
Timer(Duration(seconds: seconds), () => _toggleVolumeControls(false));
}
//#endregion
//#region Time/seek slider
double get _seekSliderValue {
if (_length.inSeconds == 0) {
return 0.0;
}
return (_time.inSeconds / _length.inSeconds * 100);
}
_seekPercent(int percent) async {
_statusRequest({
'command': 'seek',
'val': '$percent%',
});
_scheduleSingleUpdate();
}
_seekRelative(int seekTime) {
_statusRequest({
'command': 'seek',
'val': '${seekTime > 0 ? '+' : ''}${seekTime}S',
});
_scheduleSingleUpdate();
}
_toggleShowTimeLeft() {
setState(() {
_showTimeLeft = !_showTimeLeft;
});
}
//#endregion
//#region Media controls
_toggleLooping() {
_ignoreLoopStatusBefore = DateTime.now();
if (_repeat == false && _loop == false) {
_statusCommand('pl_loop');
setState(() {
_loop = true;
});
} else if (_loop == true) {
_statusCommand('pl_repeat');
setState(() {
_loop = false;
_repeat = true;
});
} else if (_repeat == true) {
_statusCommand('pl_repeat');
setState(() {
_loop = false;
_repeat = false;
});
}
}
_toggleRandom() {
_ignoreRandomStatusBefore = DateTime.now();
_statusCommand('pl_random');
setState(() {
_random = !_random;
});
}
_setRate(double rate) {
_ignoreRateStatusBefore = DateTime.now();
_statusRequest({
'command': 'rate',
'val': rate.toStringAsFixed(2),
});
}
_stop() {
_statusCommand('pl_stop');
}
_previous() {
_statusCommand('pl_previous');
}
_play(PlaylistItem item) {
_statusRequest({
'command': 'pl_play',
'id': item.id,
});
_scheduleSingleUpdate();
}
_pause() {
// Preempt the expected state so the button feels more responsive
setState(() {
_state = (_state == 'playing' ? 'paused' : 'playing');
});
_statusCommand('pl_pause');
}
_next() {
_statusCommand('pl_next');
}
_openMedia() async {
BrowseResult? result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OpenMedia(
prefs: widget.prefs,
settings: widget.settings,
),
),
);
if (result == null) {
return;
}
_statusRequest({
'command':
result.intent == BrowseResultIntent.play ? 'in_play' : 'in_enqueue',
'input': result.item.playlistUri,
});
_scheduleSingleUpdate();
}
//#endregion
@override
Widget build(BuildContext context) {
var theme = Theme.of(context);
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
Material(
color: _headerFooterBgColor,
child: ListTile(
contentPadding: const EdgeInsets.only(left: 14),
dense: widget.settings.dense,
title: Text(
_playing == null && _title.isEmpty
? 'Remote Control for VLC 1.5.0'
: _playing?.title ??
cleanVideoTitle(_title.split(RegExp(r'[\\/]')).last),
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.bold),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Visibility(
visible: !_pollingTicker.isActive,
child: IconButton(
icon: const Icon(Icons.refresh),
onPressed: _updateStatusAndPlaylist,
tooltip: 'Refresh VLC status',
),
),
Visibility(
visible: _lastStatusResponseCode == 200,
child: GestureDetector(
onLongPress: _toggleEqualizer,
child: IconButton(
color: _equalizer?.enabled == true
? theme.primaryColor
: null,
icon: const Icon(Icons.equalizer),
onPressed: _showEqualizer,
),
),
),
Visibility(
visible: _lastStatusResponseCode == 200,
child: PopupMenuButton<_PopupMenuChoice>(
onSelected: _onPopupMenuChoice,
itemBuilder: (context) {
return [
PopupMenuItem(
value: _PopupMenuChoice.subtitleTrack,
enabled:
(_lastStatusResponse?.subtitleTracks ?? [])
.isNotEmpty,
child: ListTile(
dense: widget.settings.dense,
leading: const Icon(Icons.subtitles),
title: const Text('Subtitle track'),
enabled:
(_lastStatusResponse?.subtitleTracks ?? [])
.isNotEmpty,
),
),
PopupMenuItem(
value: _PopupMenuChoice.audioTrack,
enabled: (_lastStatusResponse?.audioTracks ?? [])
.length >
1,
child: ListTile(
dense: widget.settings.dense,
leading: const Icon(Icons.audiotrack),
title: const Text('Audio track'),
enabled:
(_lastStatusResponse?.audioTracks ?? [])
.length >
1,
),
),
PopupMenuItem(
value: _PopupMenuChoice.fullscreen,
enabled: _playing != null &&
(_playing!.isVideo || _playing!.isWeb),
child: ListTile(
dense: widget.settings.dense,
leading: Icon(Icons.fullscreen,
color: _lastStatusResponse != null &&
_lastStatusResponse!.fullscreen
? theme.primaryColor
: null),
title: const Text('Fullscreen'),
enabled: _playing != null &&
(_playing!.isVideo || _playing!.isWeb),
),
),
PopupMenuItem(
value: _PopupMenuChoice.snapshot,
enabled: _playing != null &&
(_playing!.isVideo || _playing!.isWeb),
child: ListTile(
dense: widget.settings.dense,
leading: const Icon(Icons.image),
title: const Text('Take snapshot'),
enabled: _playing != null &&
(_playing!.isVideo || _playing!.isWeb),
),
),
PopupMenuItem(
value: _PopupMenuChoice.playbackSpeed,
child: ListTile(
dense: widget.settings.dense,
leading: const Icon(Icons.directions_run),
title: const Text('Playback speed'),
),
),
PopupMenuItem(
value: _PopupMenuChoice.emptyPlaylist,
enabled: _lastStatusResponse != null,
child: ListTile(
dense: widget.settings.dense,
leading: const Icon(Icons.clear),
title: const Text('Clear playlist'),
),
),
const PopupMenuDivider(),
PopupMenuItem(
value: _PopupMenuChoice.settings,
enabled: _lastStatusResponse != null,
child: ListTile(
dense: widget.settings.dense,
leading: const Icon(Icons.settings),
title: Text(intl('Settings')),
),
),
];
},
),
)
],
),
),
),
const Divider(height: 0),
_buildMainContent(),
if (!_showVolumeControls && !_animatingVolumeControls)
const Divider(height: 0),
_buildFooter(),
],
),
),
);
}
Widget _buildMainContent() {
final theme = Theme.of(context);
final headingStyle = theme.textTheme.subtitle1!
.copyWith(fontWeight: FontWeight.bold, color: theme.primaryColor);
if (!widget.settings.connection.hasIp) {
return Expanded(
child: ListView(padding: const EdgeInsets.all(16), children: [
Text('Remote Control for VLC Setup',
style: theme.textTheme.headline5),
const SizedBox(height: 16),
Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Text('1. VLC configuration', style: headingStyle),
const SizedBox(height: 8),
const Text(
'A step-by-step guide to enabling VLC\'s web interface for remote control:'),
const SizedBox(height: 8),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: theme.buttonTheme.colorScheme!.primary,
onPrimary: Colors.white,
),
onPressed: _showConfigurationGuide,
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Icon(Icons.traffic),
SizedBox(width: 8.0),
Text('VLC Configuration Guide'),
],
),
),
]),
const Divider(height: 48, color: Colors.black87),
Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Text('2. Automatic connection', style: headingStyle),
const SizedBox(height: 8),
const Text(
'Once VLC is configured, scan your local network to try to connect automatically:'),
const SizedBox(height: 8),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: theme.buttonTheme.colorScheme!.primary,
onPrimary: Colors.white,
),
onPressed: !_autoConnecting ? _autoConnect : null,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
!_autoConnecting
? const Icon(Icons.computer)
: const Padding(
padding: EdgeInsets.all(4.0),
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Colors.white),
),
),
),
const SizedBox(width: 8.0),
const Text('Scan Network for VLC'),
],
),
),
if (_autoConnectHost != null)
ListTile(
contentPadding: EdgeInsets.zero,
dense: widget.settings.dense,
leading: const Icon(
Icons.check,
color: Colors.green,
),
title: Text(_autoConnectHost!),
),
if (_autoConnectError != null)
ListTile(
contentPadding: EdgeInsets.zero,
dense: widget.settings.dense,
leading: const Icon(
Icons.error,
color: Colors.redAccent,
),
title: Text(_autoConnectError!),
)
]),
const Divider(height: 48, color: Colors.black87),
Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
Text('3. Manual connection', style: headingStyle),
const SizedBox(height: 8),
const Text(
'If automatic connection doesn\'t work, manually configure connection details:'),
const SizedBox(height: 8),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: theme.buttonTheme.colorScheme!.primary,
onPrimary: Colors.white,
),
onPressed: _showSettings,
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Icon(Icons.settings),
SizedBox(width: 8.0),
Text('Configure VLC Connection'),
],
),
)
]),
]),
);
}
return Expanded(
child: Stack(
children: [
if (widget.settings.blurredCoverBg &&
_playing != null &&
_playing!.isAudio &&
_backgroundArtUrl != null)
Positioned.fill(
child: Opacity(
opacity: .15,
child: ClipRect(
child: ImageFiltered(
imageFilter: ImageFilter.blur(
sigmaX: 2,
sigmaY: 2,
),
child: _buildBackgroundImage(),
),
),
),
),
Scrollbar(
child: ListView.builder(
controller: _scrollController,
itemCount: _playlist.length,
itemBuilder: (context, index) {
var item = _playlist[index];
var icon = item.icon;
if (item.current) {
switch (_state) {
case 'stopped':
icon = Icons.stop;
break;
case 'paused':
icon = Icons.pause;
break;
case 'playing':
icon = Icons.play_arrow;
break;
}
}
return ListTile(
dense: widget.settings.dense,
selected: item.current,
leading: Icon(icon),
title: Text(
item.title,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight:
item.current ? FontWeight.bold : FontWeight.normal,
),
),
subtitle:
item.current && _artist.isNotEmpty ? Text(_artist) : null,
trailing: !item.duration.isNegative
? Text(formatTime(item.duration),
style: item.current
? TextStyle(color: theme.primaryColor)
: null)
: null,
onTap: () {
if (item.current) {
_pause();
} else {
_play(item);
}
},
onLongPress: () {
_deletePlaylistItem(item);
},
);
},
),
),
if (_playlist.isEmpty)
Positioned.fill(
child: Padding(
padding: const EdgeInsets.all(32),
child: _lastPlaylistResponseCode == 200
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FractionallySizedBox(
widthFactor: 0.75,
child: Image.asset('assets/icon-512.png'),
),
const SizedBox(height: 16),
Text(
'Connected to VLC ${_lastStatusResponse?.version}'),
],
),
)
: ConnectionAnimation(showSettings: _showSettings),
),
),
Positioned(
right: 16,
bottom: 16,
child: TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0, end: _showFab ? 1 : 0),
duration: const Duration(milliseconds: 250),
curve: _showFab ? Curves.easeOut : Curves.easeIn,
builder: (context, scale, child) => ScaleTransition(
scale: AlwaysStoppedAnimation<double>(scale),
child: FloatingActionButton(
onPressed: _openMedia,
child: const Icon(
Icons.eject,
color: Colors.white,
),
),
),
),
),
Positioned.fill(
child: Column(
children: <Widget>[
const Spacer(),
TweenAnimationBuilder<Offset>(
tween: Tween<Offset>(
begin: const Offset(0, 1),
end: Offset(0, _showVolumeControls ? 0 : 1)),
duration: const Duration(milliseconds: 250),
curve: _showVolumeControls ? Curves.easeOut : Curves.easeIn,
onEnd: () {
setState(() {
_animatingVolumeControls = false;
});
},
builder: (context, offset, child) => SlideTransition(
position: AlwaysStoppedAnimation<Offset>(offset),
child: child,
),
child: _buildVolumeControls(),
),
],
),
),
],
),
);
}
Widget _buildBackgroundImage() {
if (_reusingBackgroundArt) {
return Image(
image: NetworkImage(_backgroundArtUrl!, headers: _authHeaders),
gaplessPlayback: true,
fit: BoxFit.cover,
);
}
return FadeInImage(
imageErrorBuilder: (_, __, ___) => const SizedBox(),
placeholder: MemoryImage(kTransparentImage),
image: NetworkImage(_backgroundArtUrl!, headers: _authHeaders),
fit: BoxFit.cover,
);
}
Widget _buildVolumeControls() {
return Column(
children: <Widget>[
const Divider(height: 0),
Container(
color: _headerFooterBgColor,
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Material(
color: Colors.transparent,
child: Row(
children: <Widget>[
// Volume down
IconButton(
icon: const Icon(Icons.remove),
tooltip: 'Decrease volume',
onPressed: _volume > 0
? () {
if (!_showVolumeControls) {
_showVolumeControls = true;
}
_setVolumeRelative(-25);
_scheduleHidingVolumeControls(2);
}
: null,
),
// Volume slider
Expanded(
flex: 1,
child: Slider(
label: '${_volumeSliderValue.round()}%',
divisions: 200,
max: 200,
value: _volumeSliderValue,
onChangeStart: (percent) {
setState(() {
_draggingVolume = true;
if (!_showVolumeControls) {
_showVolumeControls = true;
}
});
_cancelHidingVolumeControls();
},
onChanged: (percent) {
setState(() {
_volume = _scaleVolumePercent(percent);
});
Throttle.milliseconds(_sliderThrottleMilliseconds,
_setVolumePercent, [percent], {#finished: false});
},
onChangeEnd: (percent) {
_setVolumePercent(percent);
if (percent == 0.0) {
_preMuteVolume = null;
}
setState(() {
_draggingVolume = false;
});
_scheduleHidingVolumeControls(2);
},
),
),
// Volume up
IconButton(
icon: const Icon(Icons.add),
tooltip: 'Increase volume',
onPressed: _volume < 512
? () {
if (!_showVolumeControls) {
_showVolumeControls = true;
}
_setVolumeRelative(25);
_scheduleHidingVolumeControls(2);
}
: null,
),
],
),
),
),
],
);
}
Widget _buildFooter() {
var theme = Theme.of(context);
return Visibility(
visible:
widget.settings.connection.isValid && _lastStatusResponseCode == 200,
child: Container(
color: _headerFooterBgColor,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 14),
child: Row(
children: <Widget>[
Builder(
builder: (context) => GestureDetector(
onTap: () {
_togglePolling(context);
},
child: Text(
_state != 'stopped' ? formatTime(_time) : '––:––',
style: TextStyle(
color: _pollingTicker.isActive
? theme.textTheme.bodyText2!.color
: theme.disabledColor,
),
),
),
),
Expanded(
child: Slider(
divisions: 100,
max: _state != 'stopped' ? 100 : 0,
value: _seekSliderValue,
onChangeStart: (percent) {
setState(() {
_draggingTime = true;
});
},
onChanged: (percent) {
setState(() {
_time = Duration(
seconds:
(_length.inSeconds / 100 * percent).round(),
);
});
},
onChangeEnd: (percent) async {
await _seekPercent(percent.round());
setState(() {
_draggingTime = false;
});
},
),
),
GestureDetector(
onTap: _toggleShowTimeLeft,
child: Text(
_state != 'stopped' && _length != Duration.zero
? _showTimeLeft
? '-${formatTime(_length - _time)}'
: formatTime(_length)
: '––:––',
),
),
const SizedBox(width: 12),
Builder(
builder: (context) => GestureDetector(
onTap: _toggleVolumeControls,
onLongPress: _toggleMute,
child: Icon(
_volume == 0
? Icons.volume_off
: _volume < 102
? Icons.volume_mute
: _volume < 218
? Icons.volume_down
: Icons.volume_up,
color: Colors.black,
),
),
)
],
),
),
Padding(
padding:
const EdgeInsets.only(left: 9, right: 9, bottom: 6, top: 3),
child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
GestureDetector(
onTap: _toggleLooping,
child: Icon(
_repeat ? Icons.repeat_one : Icons.repeat,
color: _repeat || _loop
? theme.primaryColor
: theme.disabledColor,
size: 30,
),
),
const Expanded(child: VerticalDivider()),
GestureDetector(
onTap: _previous,
child: const Icon(
Icons.skip_previous,
color: Colors.black,
size: 30,
),
),
const Expanded(child: VerticalDivider()),
// Rewind button
GestureDetector(
child: const Icon(
Icons.fast_rewind,
color: Colors.black,
size: 30,
),
onTap: () {
_seekRelative(-10);
},
),
// Play/pause button
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: GestureDetector(
onTap: _pause,
onLongPress: _stop,
child: TweenAnimationBuilder<double>(
tween: Tween<double>(
begin: 0.0,
end: _state == 'paused' || _state == 'stopped'
? 0.0
: 1.0),
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut,
builder: (context, progress, child) => AnimatedIcon(
color: Colors.black,
size: 42,
icon: AnimatedIcons.play_pause,
progress: AlwaysStoppedAnimation<double>(progress),
),
),
),
),
// Fast forward
GestureDetector(
child: const Icon(
Icons.fast_forward,
color: Colors.black,
size: 30,
),
onTap: () {
_seekRelative(10);
},
),
const Expanded(child: VerticalDivider()),
GestureDetector(
onTap: _next,
child: const Icon(
Icons.skip_next,
color: Colors.black,
size: 30,
),
),
const Expanded(child: VerticalDivider()),
GestureDetector(
onTap: _toggleRandom,
child: Icon(
Icons.shuffle,
color: _random ? theme.primaryColor : theme.disabledColor,
size: 30,
),
),
],
),
)
],
),
),
);
}
}
class ConnectionAnimation extends StatefulWidget {
final VoidCallback showSettings;
const ConnectionAnimation({Key? key, required this.showSettings})
: super(key: key);
@override
State<StatefulWidget> createState() => _ConnectionAnimationState();
}
class _ConnectionAnimationState extends State<ConnectionAnimation>
with TickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 2000),
)..repeat();
late final Animation<int> _animation =
IntTween(begin: 0, end: 3).animate(CurvedAnimation(
parent: _controller,
curve: Curves.easeInOut,
));
@override
dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
var theme = Theme.of(context);
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Stack(
alignment: AlignmentDirectional.center,
children: <Widget>[
FractionallySizedBox(
widthFactor: 0.75,
child: Image.asset('assets/cone.png'),
),
AnimatedBuilder(
animation: _animation,
builder: (BuildContext context, Widget? child) {
return FractionallySizedBox(
widthFactor: 0.75,
child: Image.asset(
'assets/signal-${_animation.value}.png',
),
);
},
)
],
),
const SizedBox(height: 16),
const Text('Trying to connect to VLC…'),
const SizedBox(height: 16),
IconButton(
color: theme.textTheme.caption!.color,
iconSize: 48,
icon: const Icon(Icons.settings),
onPressed: widget.showSettings,
)
],
),
);
}
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/equalizer_screen.dart | import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:just_throttle_it/just_throttle_it.dart';
import 'models.dart';
import 'widgets.dart';
String _decibelsToString(double db) {
var string = db.toStringAsFixed(1);
if (string == '-0.0') {
string = '0.0';
}
return string;
}
var _frequencies = [
'60Hz',
'170Hz',
'310Hz',
'600Hz',
'1KHz',
'3KHz',
'6KHz',
'12KHz',
'14KHz',
'16KHz'
];
class EqualizerScreen extends StatefulWidget {
final Equalizer equalizer;
final Stream<Equalizer?> equalizerStream;
final Future<Equalizer?> Function(bool enabled) onToggleEnabled;
final Future<Equalizer?> Function(int presetId) onPresetChange;
final Future<Equalizer?> Function(String db) onPreampChange;
final Future<Equalizer?> Function(int bandId, String db) onBandChange;
const EqualizerScreen({
Key? key,
required this.equalizer,
required this.equalizerStream,
required this.onToggleEnabled,
required this.onPresetChange,
required this.onPreampChange,
required this.onBandChange,
}) : super(key: key);
@override
State<EqualizerScreen> createState() => _EqualizerScreenState();
}
class _EqualizerScreenState extends State<EqualizerScreen> {
/// The most recent equalizer status from VLC.
late Equalizer _equalizer = widget.equalizer;
/// Used to listen for equalizer status updates from VLC.
late final StreamSubscription _equalizerSubscription =
widget.equalizerStream.listen(_onEqualizer);
/// TODO Extract preset settings from VLC and use their preamp and band values to match a preset name
/// The last-selected preset - selected preset info isn't available from VLC.
Preset? _preset;
/// The value for the Preamp slider during and after finishing dragging it.
///
/// This will be removed once the preamp value from a VLC status update
/// matches it.
double? _preamp;
/// Used to ignore equalizer status updates VLC after a band change finishes
/// while sending requests to update equalizer bands.
bool _ignoreStatusUpdates = false;
/// When `true`, equalizer bands close to the band being adjusted will be
/// adjusted in the same direction proportional to the amount the band has
/// changed, falling off as proximity to the changing band decreases.
bool _snapBands = true;
/// The id/index of the band slider currently being dragged.
int? _draggingBand;
/// The initial equalizer state when a band slider started dragging.- used to
/// calculate values for other bands when [_snapBands] is `true.
///
/// To prevent band values jumping to their former values after a drag
/// finishes, values for modified bands are stored in this object, which is
/// used for display until equalizer band values from VLC status updates match
/// its values.
Equalizer? _draggingEqualizer;
/// The value [_draggingBand] had when its drag started
///
/// Used with [_dragValue] to calculate the delta when snapping bands.
double? _dragStartValue;
/// The current value of the band being dragged.
double? _dragValue;
@override
void dispose() {
_equalizerSubscription.cancel();
super.dispose();
}
_onEqualizer(Equalizer? equalizer) {
if (equalizer == null) {
Navigator.pop(context);
return;
}
if (_ignoreStatusUpdates) {
return;
}
setState(() {
// Get rid of the equalizer containing values from a finished EQ change
// once the equalizer from VLC status updates matches it.
if (_draggingBand == null &&
_draggingEqualizer != null &&
_draggingEqualizer!.bands.every((band) =>
_decibelsToString(band.value) ==
_decibelsToString(equalizer.bands[band.id].value))) {
_draggingEqualizer = null;
}
_equalizer = equalizer;
});
}
_toggleEnabled(enabled) async {
Equalizer? equalizer = await widget.onToggleEnabled(enabled);
if (equalizer == null) {
if (mounted) {
Navigator.pop(context);
}
return;
}
setState(() {
_equalizer = equalizer;
});
}
_choosePreset() async {
var preset = await showDialog(
context: context,
builder: (context) => SimpleDialog(
title: const Text('Preset'),
children: _equalizer.presets
.map((preset) => SimpleDialogOption(
child: Text(preset.name),
onPressed: () {
Navigator.pop(context, preset);
},
))
.toList(),
),
);
if (preset == null) {
return;
}
setState(() {
_preset = preset;
});
var equalizer = await widget.onPresetChange(preset.id);
if (equalizer == null) {
if (mounted) {
Navigator.pop(context);
}
return;
}
setState(() {
_equalizer = equalizer;
});
}
_onPreampChanged(preamp) async {
var equalizer = await widget.onPreampChange(_decibelsToString(preamp));
if (equalizer == null) {
if (mounted) {
Navigator.pop(context);
}
return;
}
setState(() {
_equalizer = equalizer;
_preamp = null;
});
}
double _getBandValue(int band) {
// Not dragging, use the current value
// If we finished changing a band, use the new values until they're current
if (_draggingBand == null) {
return (_draggingEqualizer ?? _equalizer).bands[band].value;
}
// The dragging band always uses the drag value
if (band == _draggingBand) {
return _dragValue!;
}
// If we're not snapping, other bands use the current value
if (!_snapBands) {
return _equalizer.bands[band].value;
}
// Otherwise add portions of the size of the change to neighbouring bands
var distance = (band - _draggingBand!).abs();
switch (distance) {
case 1:
return (_draggingEqualizer!.bands[band].value +
((_dragValue! - _dragStartValue!) / 2))
.clamp(-20.0, 20.0);
case 2:
return (_draggingEqualizer!.bands[band].value +
((_dragValue! - _dragStartValue!) / 8))
.clamp(-20.0, 20.0);
case 3:
return (_draggingEqualizer!.bands[band].value +
((_dragValue! - _dragStartValue!) / 40))
.clamp(-20.0, 20.0);
default:
return _equalizer.bands[band].value;
}
}
_onBandChangeStart(int band, double value) {
setState(() {
_draggingEqualizer = _equalizer;
_draggingBand = band;
_dragStartValue = value;
_dragValue = value;
});
}
_onBandChanged(double value) {
setState(() {
_dragValue = value;
});
}
_onBandChangeEnd(double value) async {
List<Band> bandChanges = [];
if (!_snapBands) {
_draggingEqualizer!.bands[_draggingBand!].value = value;
bandChanges.add(Band(_draggingBand!, value));
} else {
for (int band = math.max(0, _draggingBand! - 3);
band < math.min(_frequencies.length, _draggingBand! + 4);
band++) {
var value = _getBandValue(band);
// Store new values to display while VLC status catches up
_draggingEqualizer!.bands[band].value = value;
bandChanges.add(Band(band, value));
}
}
setState(() {
_draggingBand = null;
_dragStartValue = null;
_dragValue = null;
});
_ignoreStatusUpdates = true;
await Future.wait(bandChanges.map(
(band) => widget.onBandChange(band.id, _decibelsToString(band.value))));
_ignoreStatusUpdates = false;
}
@override
Widget build(BuildContext context) {
var theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: Text(intl('Equalizer')),
),
body: ListView(children: [
SwitchListTile(
title: const Text('Enable', textAlign: TextAlign.right),
value: _equalizer.enabled,
onChanged: _toggleEnabled,
),
if (_equalizer.enabled)
Column(children: [
ListTile(
title: const Text('Preset'),
subtitle: Text(_preset?.name ?? 'Tap to select'),
onTap: _choosePreset,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: <Widget>[
Text('Preamp', style: theme.textTheme.subtitle1),
const SizedBox(width: 16),
Expanded(
child: SliderTheme(
data: SliderTheme.of(context).copyWith(
trackShape: FullWidthTrackShape(),
),
child: Slider(
max: 20,
min: -20,
value: _preamp ?? _equalizer.preamp,
onChanged: (db) {
setState(() {
_preamp = db;
});
Throttle.milliseconds(333, widget.onPreampChange,
[_decibelsToString(db)]);
},
onChangeEnd: _onPreampChanged,
),
),
)
],
),
),
const SizedBox(height: 16),
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
for (int i = 0; i < _frequencies.length; i++)
_VerticalBandSlider(
label: _frequencies[i],
band: i,
value: _getBandValue(i),
onChangeStart: _onBandChangeStart,
onChanged: _onBandChanged,
onChangeEnd: _onBandChangeEnd,
),
]),
SwitchListTile(
title: const Text('Snap bands', textAlign: TextAlign.right),
value: _snapBands,
onChanged: (snapBands) {
setState(() {
_snapBands = snapBands;
});
},
),
]),
]),
);
}
}
class _VerticalBandSlider extends StatefulWidget {
final String label;
final int band;
final double value;
final Function(int band, double value) onChangeStart;
final Function(double value) onChanged;
final Function(double value) onChangeEnd;
const _VerticalBandSlider({
required this.label,
required this.band,
required this.value,
required this.onChangeStart,
required this.onChanged,
required this.onChangeEnd,
});
@override
_VerticalBandSliderState createState() => _VerticalBandSliderState();
}
class _VerticalBandSliderState extends State<_VerticalBandSlider> {
@override
Widget build(BuildContext context) {
return Column(children: [
const Text('+20dB', style: TextStyle(fontSize: 10)),
const SizedBox(height: 16),
RotatedBox(
quarterTurns: -1,
child: SliderTheme(
data: SliderTheme.of(context).copyWith(
trackShape: FullWidthTrackShape(),
thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 8),
overlayShape: const RoundSliderOverlayShape(overlayRadius: 16),
),
child: Slider(
max: 20,
min: -20,
value: widget.value,
onChangeStart: (value) {
widget.onChangeStart(widget.band, value);
},
onChanged: (value) {
widget.onChanged(value);
},
onChangeEnd: (value) {
widget.onChangeEnd(value);
},
),
),
),
const SizedBox(height: 16),
const Text('-20dB', style: TextStyle(fontSize: 10)),
const SizedBox(height: 8),
Text(widget.label,
style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold)),
]);
}
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/open_media.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'file_browser.dart';
import 'models.dart';
import 'utils.dart';
import 'widgets.dart';
var fileSystemItem = BrowseItem('dir', 'File System', '', 'file:///');
/// Allow some commonly-used media URLs without protocols to pass for Copied URL
/// See https://github.com/videolan/vlc/tree/master/share/lua/playlist
var probablyMediaUrlRegExp = RegExp([
r'(www\.)?dailymotion\.com/video/',
r'(www\.)?soundcloud\.com/.+/.+',
r'((www|gaming)\.)?youtube\.com/|youtu\.be/',
r'(www\.)?vimeo\.com/(channels/.+/)?\d+|player\.vimeo\.com/',
].join('|'));
var wwwRegexp = RegExp(r'www\.');
class OpenMedia extends StatefulWidget {
final SharedPreferences prefs;
final Settings settings;
const OpenMedia({
Key? key,
required this.prefs,
required this.settings,
}) : super(key: key);
@override
State<StatefulWidget> createState() => _OpenMediaState();
}
class _OpenMediaState extends State<OpenMedia> with WidgetsBindingObserver {
late List<BrowseItem> _faves;
BrowseItem? _clipboardUrlItem;
String? _otherUrl;
@override
initState() {
_faves = (jsonDecode(widget.prefs.getString('faves') ?? '[]') as List)
.map((obj) => BrowseItem.fromJson(obj))
.toList();
super.initState();
WidgetsBinding.instance.addObserver(this);
_checkClipboard();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_checkClipboard();
}
}
_checkClipboard() async {
BrowseItem? urlItem;
var data = await Clipboard.getData(Clipboard.kTextPlain);
if (data != null &&
data.text != null &&
(data.text!.startsWith(urlRegExp) ||
data.text!.startsWith(probablyMediaUrlRegExp))) {
urlItem = BrowseItem.fromUrl(data.text!);
}
setState(() {
_clipboardUrlItem = urlItem;
});
}
String get _displayUrl => _clipboardUrlItem!.uri
.replaceFirst(urlRegExp, '')
.replaceFirst(wwwRegexp, '');
_handleOtherUrl(intent) {
if (_otherUrl == null || _otherUrl!.isEmpty) {
return;
}
Navigator.pop(
context, BrowseResult(BrowseItem.fromUrl(_otherUrl!), intent));
}
bool _isFave(BrowseItem item) {
return _faves.any((fave) => item.path == fave.path);
}
_toggleFave(BrowseItem item) {
setState(() {
var index = _faves.indexWhere((fave) => item.path == fave.path);
if (index != -1) {
_faves.removeAt(index);
} else {
_faves.add(item);
}
widget.prefs.setString('faves', jsonEncode(_faves));
});
}
_selectFile(BrowseItem dir) async {
BrowseResult? result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FileBrowser(
dir: dir,
isFave: _isFave,
onToggleFave: _toggleFave,
settings: widget.settings,
),
),
);
if (result != null) {
if (mounted) {
Navigator.pop(context, result);
}
}
}
@override
Widget build(BuildContext context) {
List<Widget> listItems = <Widget>[
ListTile(
dense: widget.settings.dense,
title: const Text('File System'),
leading: const Icon(Icons.folder),
onTap: () {
_selectFile(fileSystemItem);
},
),
if (_clipboardUrlItem != null)
EnqueueMenuGestureDetector(
item: _clipboardUrlItem!,
child: ListTile(
dense: widget.settings.dense,
title: const Text('Copied URL'),
subtitle: Text(_displayUrl),
leading: const Icon(Icons.public),
onTap: () {
Navigator.pop(context,
BrowseResult(_clipboardUrlItem!, BrowseResultIntent.play));
},
),
),
ExpansionTile(
leading: const Icon(Icons.public),
title: Text('${_clipboardUrlItem != null ? 'Other ' : ''}URL'),
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
children: [
TextFormField(
keyboardType: TextInputType.url,
decoration: const InputDecoration(
border: OutlineInputBorder(),
contentPadding: EdgeInsets.symmetric(horizontal: 12),
),
onChanged: (url) {
setState(() {
_otherUrl = url;
});
},
),
Row(
children: <Widget>[
Expanded(
child: ElevatedButton(
child: const Text('Play'),
onPressed: () =>
_handleOtherUrl(BrowseResultIntent.play),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton(
child: const Text('Enqueue'),
onPressed: () =>
_handleOtherUrl(BrowseResultIntent.enqueue),
),
),
],
)
],
),
)
],
),
];
if (_faves.isNotEmpty) {
listItems.addAll([
const Divider(),
ListTile(
dense: widget.settings.dense,
title: Text('Starred', style: Theme.of(context).textTheme.subtitle2),
),
]);
listItems.addAll(_faves.map((item) => Dismissible(
key: Key(item.path),
background: const LeaveBehindView(),
child: ListTile(
dense: widget.settings.dense,
title: Text(item.name),
leading: const Icon(Icons.folder_special),
onTap: () {
_selectFile(item);
},
),
onDismissed: (direction) {
_toggleFave(item);
},
)));
}
return Scaffold(
appBar: AppBar(
title: const Text('Open Media'),
),
body: ListView(children: listItems),
);
}
}
class LeaveBehindView extends StatelessWidget {
const LeaveBehindView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
padding: const EdgeInsets.all(16.0),
child: Row(
children: const <Widget>[
Icon(Icons.delete, color: Colors.white),
Expanded(
child: Text(''),
),
Icon(Icons.delete, color: Colors.white),
],
),
);
}
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/vlc_configuration_guide.dart | import 'package:flutter/material.dart';
import 'models.dart';
import 'widgets.dart';
class VlcConfigurationGuide extends StatefulWidget {
const VlcConfigurationGuide({Key? key}) : super(key: key);
@override
State<VlcConfigurationGuide> createState() => _VlcConfigurationGuideState();
}
class _VlcConfigurationGuideState extends State<VlcConfigurationGuide> {
int _currentStep = 0;
OperatingSystem? _os;
_onOsChanged(os) {
setState(() {
_os = os;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
const Text('VLC Configuration Guide'),
if (_os != null)
Text('for ${osNames[_os]}', style: const TextStyle(fontSize: 13)),
],
),
),
body: buildBody(),
);
}
Widget buildBody() {
switch (_os) {
case OperatingSystem.macos:
return buildMacStepper();
case OperatingSystem.linux:
case OperatingSystem.windows:
return buildLinuxWindowsStepper();
default:
var theme = Theme.of(context);
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(24),
child: Wrap(
runSpacing: 16,
children: [
Text('Which operating system are you running VLC on?',
style: theme.textTheme.subtitle1),
Column(
children: OperatingSystem.values
.map((os) => RadioListTile(
title: Text(osNames[os]!),
value: os,
groupValue: _os,
onChanged: _onOsChanged,
))
.toList())
],
),
),
],
);
}
}
Widget buildLinuxWindowsStepper() {
var theme = Theme.of(context);
var os = _os.toString().split('.').last;
return Stepper(
currentStep: _currentStep,
controlsBuilder: (BuildContext context, ControlsDetails details) {
return Padding(
padding: const EdgeInsets.only(top: 16),
child: Row(
children: <Widget>[
TextButton(
style: TextButton.styleFrom(
backgroundColor: theme.primaryColor,
primary: Colors.white,
),
onPressed: details.onStepContinue,
child: Text(_currentStep == 2 ? 'FINISHED' : 'NEXT STEP'),
),
TextButton(
onPressed: details.onStepCancel,
child: const Text('PREVIOUS STEP'),
),
],
),
);
},
onStepCancel: () {
if (_currentStep > 0) {
setState(() {
_currentStep--;
});
} else {
_onOsChanged(null);
}
},
onStepContinue: () {
if (_currentStep == 2) {
Navigator.pop(context);
return;
}
setState(() {
_currentStep++;
});
},
steps: [
Step(
title: const Text('Enable VLC\'s web interface'),
content: TextAndImages(
children: <Widget>[
const Text(
'In VLC\'s menu bar, select Tools > Preferences to open the preferences window:'),
Image.asset('assets/$os-menu.png'),
const Text(
'Switch to Advanced Preferences mode by clicking the "All" radio button in the "Show settings" section at the bottom left of the window:'),
Image.asset('assets/$os-show-settings.png'),
const Text(
'Scroll down to find the "Main interfaces" section and click it:'),
Image.asset('assets/$os-main-interface.png'),
const Text(
'Check the "Web" checkbox in the "Extra interface modules" section to enable the web interface:'),
Image.asset('assets/$os-web.png'),
],
),
),
Step(
title: const Text('Set web interface password'),
content: TextAndImages(
children: <Widget>[
const Text(
'Expand the "Main interfaces" section by clicking the ">" chevron and click the "Lua" section which appears:'),
Image.asset('assets/$os-lua.png'),
const Text('Set a password in the "Lua HTTP" section:'),
Image.asset('assets/$os-password.png'),
const Text(
'Remote Control for VLC uses the password "vlcplayer" (without quotes) by default – if you set something else you\'ll have to manually configure the VLC connection.'),
const Text('Finally, click Save to save your changes.'),
],
),
),
Step(
title: const Text('Close and restart VLC'),
content: Row(
children: const <Widget>[
Text('Close and restart VLC to activate the web interface.'),
],
),
)
],
);
}
Widget buildMacStepper() {
var theme = Theme.of(context);
return Stepper(
currentStep: _currentStep,
controlsBuilder: (BuildContext context, ControlsDetails details) {
return Padding(
padding: const EdgeInsets.only(top: 16),
child: Row(
children: <Widget>[
TextButton(
style: TextButton.styleFrom(
backgroundColor: theme.primaryColor,
primary: Colors.white,
),
onPressed: details.onStepContinue,
child: Text(_currentStep == 1 ? 'FINISHED' : 'NEXT STEP'),
),
TextButton(
onPressed: details.onStepCancel,
child: const Text('PREVIOUS STEP'),
),
],
),
);
},
onStepCancel: () {
if (_currentStep > 0) {
setState(() {
_currentStep--;
});
} else {
_onOsChanged(null);
}
},
onStepContinue: () {
if (_currentStep == 1) {
Navigator.pop(context);
return;
}
setState(() {
_currentStep++;
});
},
steps: [
Step(
title: const Text('Enable VLC\'s web interface'),
content: TextAndImages(
children: <Widget>[
const Text(
'In the Menubar, select VLC > Preferences to open the preferences window:'),
Image.asset('assets/mac-menu.png'),
const Text(
'At the bottom of the "Interface" settings page, check "Enable HTTP web interface" and set a password.'),
Image.asset('assets/mac-http-interface.png'),
const Text(
'Remote Control for VLC uses the password "vlcplayer" (without quotes) by default – if you set something else you\'ll have to manually configure the VLC connection.'),
const Text('Finally, click Save to save your changes.'),
],
),
),
Step(
title: const Text('Quit and restart VLC'),
content: Row(
children: const <Widget>[
Text('Quit and restart VLC to activate the web interface.'),
],
),
)
],
);
}
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/widgets.dart | import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'models.dart';
class EnqueueMenuGestureDetector extends StatefulWidget {
final Widget child;
final BrowseItem item;
const EnqueueMenuGestureDetector(
{Key? key, required this.child, required this.item})
: super(key: key);
@override
State<EnqueueMenuGestureDetector> createState() =>
_EnqueueMenuGestureDetectorState();
}
class _EnqueueMenuGestureDetectorState
extends State<EnqueueMenuGestureDetector> {
late Offset _tapPosition;
_handleTapDown(details) {
_tapPosition = details.globalPosition;
}
_showMenu() async {
final Size size = Overlay.of(context)!.context.size!;
var intent = await showMenu(
context: context,
items: <PopupMenuItem<BrowseResultIntent>>[
const PopupMenuItem(
value: BrowseResultIntent.play,
child: Text('Play'),
),
const PopupMenuItem(
value: BrowseResultIntent.enqueue,
child: Text('Enqueue'),
),
],
position: RelativeRect.fromRect(
_tapPosition & const Size(40, 40), Offset.zero & size),
);
if (intent != null) {
if (mounted) {
Navigator.pop(context, BrowseResult(widget.item, intent));
}
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: _handleTapDown,
onLongPress: _showMenu,
child: widget.child,
);
}
}
/// A custom track shape for a [Slider] which lets it go full-width.
///
/// From https://github.com/flutter/flutter/issues/37057#issuecomment-516048356
class FullWidthTrackShape extends RoundedRectSliderTrackShape {
@override
Rect getPreferredRect({
required RenderBox parentBox,
Offset offset = Offset.zero,
required SliderThemeData sliderTheme,
bool isEnabled = false,
bool isDiscrete = false,
}) {
final double trackHeight = sliderTheme.trackHeight!;
final double trackLeft = offset.dx;
final double trackTop =
offset.dy + (parentBox.size.height - trackHeight) / 2;
final double trackWidth = parentBox.size.width;
return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
}
}
var _intlStrings = {
'Equalizer': 'Equaliser',
'Settings': 'Settings',
};
String intl(String enUsString) {
if (ui.window.locale.countryCode == 'US' ||
!_intlStrings.containsKey(enUsString)) {
return enUsString;
}
return _intlStrings[enUsString]!;
}
/// Like [Iterable.join] but for lists of Widgets.
Iterable<Widget> intersperseWidgets(Iterable<Widget> iterable,
{required Widget Function() builder}) sync* {
final iterator = iterable.iterator;
if (iterator.moveNext()) {
yield iterator.current;
while (iterator.moveNext()) {
yield builder();
yield iterator.current;
}
}
}
/// A [WhitelistingTextInputFormatter] that takes in digits `[0-9]` and periods
/// `.` only.
var ipWhitelistingTextInputFormatter =
FilteringTextInputFormatter.allow(RegExp(r'[\d.]+'));
/// Remove current focus to hide the keyboard.
removeCurrentFocus(BuildContext context) {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
}
class TextAndImages extends StatelessWidget {
final List<Widget> children;
final double spacing;
const TextAndImages({Key? key, required this.children, this.spacing = 16})
: super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: intersperseWidgets(
children.map((child) => Row(children: [
Expanded(
child: Container(
alignment: Alignment.topLeft,
child: child,
))
])),
builder: () => SizedBox(height: spacing),
).toList(),
);
}
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/file_browser.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:xml/xml.dart' as xml;
import 'models.dart';
import 'widgets.dart';
class FileBrowser extends StatefulWidget {
final BrowseItem dir;
final bool Function(BrowseItem) isFave;
final Function(BrowseItem) onToggleFave;
final Settings settings;
const FileBrowser({
Key? key,
required this.dir,
required this.isFave,
required this.onToggleFave,
required this.settings,
}) : super(key: key);
@override
State<StatefulWidget> createState() => _FileBrowserState();
}
class _FileBrowserState extends State<FileBrowser> {
bool _loading = false;
String? _errorMessage;
String? _errorDetail;
List<BrowseItem> _items = [];
@override
void initState() {
_getListing(widget.dir);
super.initState();
}
_getListing(BrowseItem dir) async {
setState(() {
_loading = true;
});
http.Response response;
assert(() {
//print('/requests/browse.xml?uri=${dir.uri}');
return true;
}());
try {
response = await http.get(
Uri.http(widget.settings.connection.authority, '/requests/browse.xml', {
'uri': dir.uri,
}),
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(':${widget.settings.connection.password}'))}',
},
).timeout(const Duration(seconds: 2));
} catch (e) {
setState(() {
_errorMessage = 'Error connecting to VLC';
_errorDetail = e.runtimeType.toString();
_loading = false;
});
return;
}
List<BrowseItem> dirs = [];
List<BrowseItem> files = [];
if (response.statusCode == 200) {
var document = xml.XmlDocument.parse(utf8.decode(response.bodyBytes));
document.findAllElements('element').forEach((el) {
var item = BrowseItem(
el.getAttribute('type') ?? '',
el.getAttribute('name') ?? '',
el.getAttribute('path') ?? '',
el.getAttribute('uri') ?? '',
);
if (item.name == '..') {
return;
}
if (item.isDir) {
dirs.add(item);
} else if (item.isSupportedMedia || item.isPlaylist) {
files.add(item);
}
});
}
dirs.sort((a, b) {
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
});
files.sort((a, b) {
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
});
setState(() {
_items = dirs + files;
_loading = false;
});
}
_handleTap(BrowseItem item) async {
if (item.isDir) {
BrowseResult? result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FileBrowser(
dir: item,
isFave: widget.isFave,
onToggleFave: widget.onToggleFave,
settings: widget.settings,
),
),
);
if (result != null) {
if (mounted) {
Navigator.pop(context, result);
}
}
} else {
Navigator.pop(context, BrowseResult(item, BrowseResultIntent.play));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.dir.title),
actions: widget.dir.path != ''
? <Widget>[
IconButton(
onPressed: () {
setState(() {
widget.onToggleFave(widget.dir);
});
},
icon: Icon(
widget.isFave(widget.dir) ? Icons.star : Icons.star_border,
color: Colors.white,
),
)
]
: null,
),
body: _renderList(),
);
}
_renderList() {
if (_loading) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[CircularProgressIndicator()],
),
);
}
if (_errorMessage != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ListTile(
leading: const Icon(
Icons.error,
color: Colors.redAccent,
size: 48,
),
title: Text(_errorMessage!),
subtitle: Text(_errorDetail!),
),
],
),
);
}
if (_items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[Text('No compatible files found')],
),
);
}
return Scrollbar(
child: ListView.separated(
itemCount: _items.length,
itemBuilder: (context, i) {
var item = _items[i];
return EnqueueMenuGestureDetector(
item: item,
child: ListTile(
dense: widget.settings.dense,
leading: Icon(item.icon),
title: Text(item.title),
enabled: !_loading,
onTap: () {
_handleTap(item);
},
),
);
},
separatorBuilder: (context, i) {
if (_items[i].isDir &&
i < _items.length - 1 &&
_items[i + 1].isFile) {
return const Divider();
}
return const SizedBox.shrink();
},
),
);
}
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/host_ip_guide.dart | import 'package:flutter/material.dart';
import 'models.dart';
import 'widgets.dart';
class HostIpGuide extends StatefulWidget {
const HostIpGuide({Key? key}) : super(key: key);
@override
State<HostIpGuide> createState() => _HostIpGuideState();
}
class _HostIpGuideState extends State<HostIpGuide> {
OperatingSystem? _os;
_onOsChanged(os) {
setState(() {
_os = os;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
const Text('Host IP Guide'),
if (_os != null)
Text('for ${osNames[_os]}', style: const TextStyle(fontSize: 13)),
],
),
),
body: buildBody(),
);
}
Widget buildBody() {
var theme = Theme.of(context);
switch (_os) {
case OperatingSystem.macos:
return ListView(padding: const EdgeInsets.all(24), children: [
TextAndImages(children: <Widget>[
const Text('From the Apple menu, select "System Preferences".'),
const Text(
'In the System Preferences window, click on the "Network" item:'),
Image.asset('assets/mac-network.png'),
const Text(
'Your IP address will be visible to the right of the Network window, as shown below:'),
Image.asset('assets/mac-ip.png'),
]),
]);
case OperatingSystem.linux:
return ListView(padding: const EdgeInsets.all(24), children: [
TextAndImages(children: <Widget>[
const Text(
'Open a Terminal – on many popular distros this can be done by pressing Ctr + Alt + T.'),
const Text(
'In the Terminal window, type "ifconfig" and press Enter:'),
Image.asset('assets/linux-terminal.png'),
const Text(
'Your host IP will be one of the "inet" IP results which appears in the output of the command:'),
Image.asset('assets/linux-ifconfig.png'),
const Text(
'Depending on how your computer is set up, there may be multiple results:'),
const Text(
'If you connect to the network via an ethernet cable, look for the inet IP under an "eth0" interface.'),
const Text(
'If you connect to the network via Wi-Fi, look for the inet IP under a "wlan0" interface.'),
]),
]);
case OperatingSystem.windows:
return ListView(padding: const EdgeInsets.all(24), children: [
TextAndImages(children: <Widget>[
const Text(
'Open a Command Prompt by pressing Win + R, typing "cmd" in the dialog which appears, and presssing Enter:'),
Image.asset('assets/windows-run.png'),
const Text(
'In the Command Prompt window, type "ipconfig" and press Enter:'),
Image.asset('assets/windows-cmd.png'),
const Text(
'Your host IP will be one of the "IPv4 Address" results which appears in the output of the command:'),
Image.asset('assets/windows-ipconfig.png'),
const Text(
'Depending on how your computer is set up, there may be multiple results:'),
const Text(
'If you connect to the network via an ethernet cable, look for the IPv4 Address under an "Ethernet adapter Ethernet" result.'),
const Text(
'If you connect to the network via Wi-Fi, look for the IPv4 Address under an "Ethernet adapter Wireless Network Connection" result.'),
]),
]);
default:
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(24),
child: Wrap(
runSpacing: 16,
children: [
Text('Which operating system are you running VLC on?',
style: theme.textTheme.subtitle1),
Column(
children: OperatingSystem.values
.map((os) => RadioListTile(
title: Text(osNames[os]!),
value: os,
groupValue: _os,
onChanged: _onOsChanged,
))
.toList())
],
),
),
],
);
}
}
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/utils.dart | var _dot = RegExp(r'\.');
var _episode = RegExp(r's\d\de\d\d', caseSensitive: false);
// From https://en.wikipedia.org/wiki/Pirated_movie_release_types#Common_abbreviations
var _source = [
'ABC',
'ATVP',
'AMZN',
'BBC',
'CBS',
'CC',
'CR',
'CW',
'DCU',
'DSNY',
'FBWatch',
'FREE',
'FOX',
'HULU',
'iP',
'LIFE',
'MTV',
'NBC',
'NICK',
'NF',
'RED',
'TF1',
'STZ',
].map((s) => RegExp.escape(s)).join('|');
// From https://en.wikipedia.org/wiki/Pirated_movie_release_types#Release_formats
var _format = [
'CAMRip',
'CAM',
'HDCAM',
'TS',
'HDTS',
'TELESYNC',
'PDVD',
'PreDVDRip',
'WP',
'WORKPRINT',
'TC',
'HDTC',
'TELECINE',
'PPV',
'PPVRip',
'SCR',
'SCREENER',
'DVDSCR',
'DVDSCREENER',
'BDSCR',
'DDC',
'R5',
'R5.LINE',
'R5.AC3.5.1.HQ',
'DVDRip',
'DVDMux',
'DVDR',
'DVD-Full',
'Full-Rip',
'ISO rip',
'lossless rip',
'untouched rip',
'DVD-5',
'DVD-9',
'DSR',
'DSRip',
'SATRip',
'DTHRip',
'DVBRip',
'HDTV',
'PDTV',
'DTVRip',
'TVRip',
'HDTVRip',
'VODRip',
'VODR',
'WEBDL',
'WEB DL',
'WEB-DL',
'HDRip',
'WEB-DLRip',
'WEBRip',
'WEB Rip',
'WEB-Rip',
'WEB',
'WEB-Cap',
'WEBCAP',
'WEB Cap',
'HC',
'HD-Rip',
'Blu-Ray',
'BluRay',
'BDRip',
'BRip',
'BRRip',
'BDMV',
'BDR',
'BD25',
'BD50',
'BD5',
'BD9',
].map((s) => RegExp.escape(s)).join('|');
var _year = r'\d{4}';
// 720p, 1080p etc.
var _res = r'\d{3,4}p?';
// DUBBED, JAPANESE, INDONESIAN etc.
var _language = r'[A-Z]+';
var _movie = RegExp(
'\\.$_year(\\.$_language)?(\\.$_res)?(\\.($_source))?\\.($_format)',
caseSensitive: false,
);
String cleanVideoTitle(String name, {bool keepExt = false}) {
if (name == '') {
return '';
}
if (_episode.hasMatch(name)) {
return dotsToSpaces(name.substring(0, _episode.firstMatch(name)!.end));
}
if (_movie.hasMatch(name)) {
return dotsToSpaces(name.substring(0, _movie.firstMatch(name)!.start));
}
return dotsToSpaces(name, keepExt: keepExt);
}
String dotsToSpaces(String s, {bool keepExt = false}) {
String ext = '';
var parts = s.split(_dot);
if (keepExt) {
ext = parts.removeLast();
}
return '${parts.join(' ')}.$ext';
}
/// [Iterable.firstWhere] doesn't work with null safety when you want to fall
/// back to returning `null`.
///
/// See https://github.com/dart-lang/sdk/issues/42947
T? firstWhereOrNull<T>(Iterable<T> iterable, bool Function(T element) test) {
for (var element in iterable) {
if (test(element)) return element;
}
return null;
}
String formatTime(Duration duration) {
String minutes = (duration.inMinutes % 60).toString().padLeft(2, '0');
String seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
return '${duration.inHours >= 1 ? '${duration.inHours}:' : ''}$minutes:$seconds';
}
/// Matches some of the protocols supported by VLC.
var urlRegExp = RegExp(r'((f|ht)tps?|mms|rts?p)://');
/*
* Trick stolen from https://gist.github.com/shubhamjain/9809108#file-vlc_http-L108
* The interface expects value between 0 and 512 while in the UI it is 0% to 200%.
* So a factor of 2.56 is used to convert 0% to 200% to a scale of 0 to 512.
*/
const volumeSliderScaleFactor = 2.56;
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/settings_screen.dart | import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:network_info_plus/network_info_plus.dart';
import 'host_ip_guide.dart';
import 'models.dart';
import 'widgets.dart';
class SettingsScreen extends StatefulWidget {
final Settings settings;
final Function onSettingsChanged;
const SettingsScreen(
{Key? key, required this.settings, required this.onSettingsChanged})
: super(key: key);
@override
State<StatefulWidget> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
Connection connection = Connection();
var ipController = TextEditingController();
var ipFocus = FocusNode();
bool ipDirty = false;
var portController = TextEditingController();
var portFocus = FocusNode();
bool portDirty = false;
var passwordController = TextEditingController();
var passwordFocus = FocusNode();
bool passwordDirty = false;
String? prefilledIpSuffix;
bool showPassword = false;
bool scanningNetwork = false;
bool testingConnection = false;
String? connectionTestResult;
String? connectionTestResultDescription;
IconData? connectionTestResultIcon;
@override
initState() {
ipController.addListener(() {
setState(() {
connection.ip = ipController.text;
});
});
portController.addListener(() {
setState(() {
connection.port = portController.text;
});
});
passwordController.addListener(() {
setState(() {
connection.password = passwordController.text;
});
});
ipController.text = widget.settings.connection.ip;
portController.text = widget.settings.connection.port;
passwordController.text = widget.settings.connection.password;
ipFocus.addListener(() {
if (!ipFocus.hasFocus) {
setState(() {
ipDirty = true;
});
}
});
portFocus.addListener(() {
if (!portFocus.hasFocus) {
setState(() {
portDirty = true;
});
}
});
passwordFocus.addListener(() {
if (!passwordFocus.hasFocus) {
setState(() {
passwordDirty = true;
});
}
});
super.initState();
if (widget.settings.connection.ip == '') {
_defaultIpPrefix();
}
}
@override
dispose() {
ipController.dispose();
ipFocus.dispose();
portController.dispose();
portFocus.dispose();
passwordController.dispose();
passwordFocus.dispose();
super.dispose();
}
_defaultIpPrefix() async {
if (await Connectivity().checkConnectivity() == ConnectivityResult.wifi) {
var ip = await NetworkInfo().getWifiIP();
if (ip != null) {
setState(() {
prefilledIpSuffix = ip.substring(0, ip.lastIndexOf('.') + 1);
ipController.text = prefilledIpSuffix!;
});
}
}
}
_testConnection() async {
removeCurrentFocus(context);
if (!connection.isValid) {
setState(() {
ipDirty = true;
portDirty = true;
passwordDirty = true;
});
return;
}
setState(() {
connectionTestResult = null;
connectionTestResultIcon = null;
connectionTestResultDescription = null;
testingConnection = true;
});
String result;
String description;
IconData icon;
try {
var response = await http.get(
Uri.http(
'${ipController.text}:${portController.text}',
'/requests/status.xml',
),
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(':${passwordController.text}'))}'
}).timeout(const Duration(seconds: 2));
if (response.statusCode == 200) {
widget.settings.connection = connection;
widget.onSettingsChanged();
result = 'Connection successful';
description = 'Connection settings saved';
icon = Icons.check;
} else {
icon = Icons.error;
if (response.statusCode == 401) {
result = 'Password is invalid';
description = 'Tap the eye icon to check your password';
} else {
result = 'Unexpected response';
description = 'Status code: ${response.statusCode}';
}
}
} catch (e) {
description = 'Check the IP and port settings';
icon = Icons.error;
if (e is TimeoutException) {
result = 'Connection timed out';
} else if (e is SocketException) {
result = 'Connection error';
} else {
result = 'Connection error: ${e.runtimeType}';
}
}
setState(() {
connectionTestResult = result;
connectionTestResultDescription = description;
connectionTestResultIcon = icon;
testingConnection = false;
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final headingStyle = theme.textTheme.subtitle1!
.copyWith(fontWeight: FontWeight.bold, color: theme.primaryColor);
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('Settings'),
),
body: ListView(children: <Widget>[
ListTile(
dense: widget.settings.dense,
title: Text(
'VLC connection',
style: headingStyle,
),
),
ListTile(
dense: widget.settings.dense,
title: TextField(
controller: ipController,
focusNode: ipFocus,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [ipWhitelistingTextInputFormatter],
decoration: InputDecoration(
isDense: widget.settings.dense,
icon: const Icon(Icons.computer),
labelText: 'Host IP',
errorText: ipDirty ? connection.ipError : null,
helperText: prefilledIpSuffix != null &&
connection.ip == prefilledIpSuffix
? 'Suffix pre-filled from your Wi-Fi IP'
: null,
),
),
trailing: IconButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => const HostIpGuide()));
},
tooltip: 'Get help finding your IP',
icon: Icon(Icons.help, color: theme.primaryColor),
),
),
ListTile(
dense: widget.settings.dense,
title: TextField(
controller: passwordController,
focusNode: passwordFocus,
obscureText: !showPassword,
decoration: InputDecoration(
isDense: widget.settings.dense,
icon: const Icon(Icons.vpn_key),
labelText: 'Password',
errorText: passwordDirty ? connection.passwordError : null,
),
),
trailing: IconButton(
onPressed: () {
setState(() {
showPassword = !showPassword;
});
},
tooltip: 'Toggle password visibility',
icon: Icon(Icons.remove_red_eye,
color: showPassword ? theme.primaryColor : null),
),
),
ListTile(
dense: widget.settings.dense,
title: TextField(
controller: portController,
focusNode: portFocus,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
decoration: InputDecoration(
isDense: widget.settings.dense,
icon: const Icon(Icons.input),
labelText: 'Port (default: 8080)',
errorText: portDirty ? connection.portError : null,
helperText: 'Advanced use only'),
),
),
ListTile(
dense: widget.settings.dense,
title: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: theme.buttonTheme.colorScheme!.primary,
onPrimary: Colors.white,
),
onPressed: !testingConnection ? _testConnection : null,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
testingConnection
? const Padding(
padding: EdgeInsets.all(4.0),
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Colors.white)),
),
)
: const Icon(Icons.network_check),
const SizedBox(width: 8.0),
const Text('Test & Save Connection'),
],
),
),
),
if (connectionTestResult != null)
ListTile(
dense: widget.settings.dense,
leading: Icon(
connectionTestResultIcon,
color: connectionTestResultIcon == Icons.check
? Colors.green
: Colors.redAccent,
),
title: Text(connectionTestResult!),
subtitle: connectionTestResultDescription != null
? Text(connectionTestResultDescription!)
: null,
),
const Divider(),
ListTile(
dense: widget.settings.dense,
title: Text(
'Display options',
style: headingStyle,
),
),
CheckboxListTile(
title: const Text('Compact display'),
value: widget.settings.dense,
dense: widget.settings.dense,
onChanged: (dense) {
setState(() {
widget.settings.dense = dense ?? false;
widget.onSettingsChanged();
});
},
),
CheckboxListTile(
title: const Text('Blurred cover background'),
subtitle: const Text('When available for audio files'),
value: widget.settings.blurredCoverBg,
dense: widget.settings.dense,
onChanged: (dense) {
setState(() {
widget.settings.blurredCoverBg = dense ?? false;
widget.onSettingsChanged();
});
},
),
]),
);
}
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/models.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xml/xml.dart' as xml;
import 'utils.dart';
var _videoExtensions = RegExp(
r'\.(3g2|3gp|3gp2|3gpp|amv|asf|avi|divx|drc|dv|f4v|flv|gvi|gxf|ismv|iso|m1v|m2v|m2t|m2ts|m4v|mkv|mov|mp2|mp2v|mp4|mp4v|mpe|mpeg|mpeg1|mpeg2|mpeg4|mpg|mpv2|mts|mtv|mxf|mxg|nsv|nut|nuv|ogm|ogv|ogx|ps|rec|rm|rmvb|tod|ts|tts|vob|vro|webm|wm|wmv|wtv|xesc)$');
var _audioExtensions = RegExp(
r'\.(3ga|a52|aac|ac3|adt|adts|aif|aifc|aiff|alac|amr|aob|ape|awb|caf|dts|flac|it|m4a|m4b|m4p|mid|mka|mlp|mod|mpa|mp1|mp2|mp3|mpc|mpga|oga|ogg|oma|opus|ra|ram|rmi|s3m|spx|tta|voc|vqf|w64|wav|wma|wv|xa|xm)$');
var _playlistExtensions = RegExp(
r'\.(asx|b4s|cue|ifo|m3u|m3u8|pls|ram|rar|sdp|vlc|xspf|wax|wvx|zip|conf)');
var _audioTranslations = RegExp(
r"^(Audio|_Audio|Ameslaw|Aodio|Audioa|Audiu|Deng|Dźwięk|Ekirikuhurirwa|Endobozi|Fuaim|Fuaim|Garsas|Hang|Hljóð|Leo|Ljud|Lyd|M_adungan|Ma giwinyo|Odio|Ojoo|Oudio|Ovoz|Sain|Ses|Sonido|Səs|Umsindo|Zvok|Zvuk|Zëri|Àudio|Áudio|Ääni|Ήχος|Аудио|Аўдыё|Дуу|Дыбыс|Звук|Ձայն|שמע|آڈیو, صدا|ئۈن|آڈیو|دەنگ|صدا|غږيز|अडिअ'|अडियो|आडियो|ध्वनी|অডিঅ'|অডিও|ਆਡੀਓ|ઓડિયો|ଅଡ଼ିଓ|ஒலி|శ్రవ్యకం|ಧ್ವನಿ|ഓഡിയോ|ශ්රව්ය|เสียง|အသံ|აუდიო|ተሰሚ|ድምፅ|អូឌីយ៉ូ|オーディオ|音訊|音频|오디오)$");
var _codecTranslations = RegExp(
r"^(Codec|Bonez|Codifica|Codificador|Cudecu|Còdec|Códec|Dekko|Enkusike|i-Codec|Kodavimas|Kodek|Kodeka|Kodeks|Kodlayıcı/Çözücü|Koodek|Koodekki|Kóðalykill (codec)|Kôdek|Scéim Comhbhrúite|Кодек|Кодэк|Կոդեկ|מקודד/מפענח|كود يەشكۈچ|كوديك|کوڈیک|کوډېک|کُدک|کۆدێک|कोडेक|কোডেক|કોડેક|କୋଡେକ୍|கோடக்|కొడెక్|ಸಂಕೇತಕ|കോഡെക്ക്|කොඩෙක්|ตัวอ่าน-ลงรหัส|კოდეკი|ኮዴክ|កូដិក|コーデック|編解碼器|编解码器|코덱)$");
var _descriptionTranslations = RegExp(
r"^(Description|Apraksts|Aprašymas|Açıklama|Beschreibung|Beschrijving|Beskriuwing|Beskrivelse|Beskrivning|Beskrywing|Cifagol|Cur síos|Descrición|Descriere|Descripcion|Descripció|Descripción|Descrizion|Descrizione|Descrição|Deskribapena|Deskripsi|Deskrivadur|Discrijhaedje|Discrizzione|Disgrifiad|Ennyinyonyola|Enshoborora|Fa'amatalaga|Hedef|Incazelo|Keterangan|Kirjeldus|Kuvaus|Leírás|Lýsing|Mô tả|Opis|Popis|Përshkrimi|Skildring|Ta’rifi|Te lok|Tuairisgeul|Περιγραφή|Апісанне|Баяндама|Опис|Описание|Сипаттама|Тайлбар|Тасвирлама|Նկարագրություն|תיאור|الوصف|سپړاوی|شرح|وضاحت|پەسن|چۈشەندۈرۈش|बेखेवथि|वर्णन|विवरण|বর্ণনা|বিবরণ|বিৱৰণ|ਵੇਰਵਾ|વર્ણન|ବିବରଣୀ|விவரம்|వివరణ|ವಿವರಣೆ|വിവരണം|විස්තරය|รายละเอียด|ဖော်ပြချက်|აღწერილობა|መግለጫ|សេចក្ដីពណ៌នា|描述|說明|説明|설명)$");
var _languageTranslations = RegExp(
r"^(Language|Bahasa|Bahasa|Cànan|Dil|Gagana|Gjuha|Hizkuntza|Iaith|Idioma|Jazyk|Jezik|Kalba|Keel|Kieli|Langue|Leb|Lenga|Lenghe|Limbă|Lingaedje|Lingua|Llingua|Ngôn ngữ|Nyelv|Olulimi|Orurimi|Sprache|Språk|Taal|Teanga|Til|Tungumál|Ulimi|Valoda|Wybór języka|Yezh|Ziman|Ɗemngal|Γλώσσα|Език|Мова|Тел|Тил|Тілі|Хэл|Язык|Језик|Լեզու|שפה|اللغة|تىل|زبان|زمان|ژبه|भाषा|राव|ভাষা|ਭਾਸ਼ਾ|ભાષા|ଭାଷା|மொழி|భాష|ಭಾಷೆ|ഭാഷ|භාෂාව|ภาษา|ဘာသာစကား|ენა|ቋንቋ|ቋንቋ|ភាសា|言語|語言|语言|언어)$");
var _subtitleTranslations = RegExp(
r"^(Subtitle|Altyazı|Azpititulua|Binnivîs/OSD|Emitwe|Felirat|Fo-thiotal|Fotheideal|Gagana fa'aliliu|Isdeitlau|Istitl|Izihlokwana|Legenda|Legendas|Lestiitol|Napisy|Omutwe ogwokubiri|Onderskrif|Ondertitel|Phụ đề|Podnapisi|Podnaslov|Podtitl|Sarikata|Sortite|Sostítols|Sot titul|Sottotitoli|Sottutitulu|Sous-titres|Subtiiter|Subtitlu|Subtitol|Subtitr|Subtitrai|Subtitrs|Subtitulo|Subtítol|Subtítulo|Subtítulos|Subtítulu|Tekstitys|Terjemahan|Texti|Titra|Titulky|Titulky|Undertekst|Undertext|Undertitel|Υπότιτλος|Дэд бичвэр|Превод|Субтитр|Субтитри|Субтитрлер|Субтитры|Субтитрі|Субтытры|Титл|Ենթագիր|अनुवाद पट्टी|उपशीर्षक|दालाय-बिमुं|উপশিৰোনাম|বিকল্প নাম|সাবটাইটেল|ਸਬ-ਟਾਈਟਲ|ઉપશીર્ષક|ଉପଟାଇଟେଲ୍|துணை உரை|ఉపశీర్షిక|ಉಪಶೀರ್ಷಿಕೆ|ഉപശീര്ഷകം|උපසිරැසි|บทบรรยาย|စာတန်းထိုး|ტიტრები|ንዑስ አርእስት|ጽሁፋዊ ትርጉሞች|ចំណងជើងរង|字幕|자막)$");
var _typeTranslations = RegExp(
r"^(Type|Cineál|Cure|Ekyika|Fannu|Handiika|Itū'āiga|Jenis|Kite|Liik|Loại|Math|Mota|Rizh|Seòrsa|Sôre|Tegund|Tip|Tipas|Tipe|Tipi|Tipo|Tips|Tipu|Tipus|Turi|Typ|Typo|Tyyppi|Típus|Tür|Uhlobo|Vrsta|Τύπος|Врста|Тип|Түрі|Түрү|Төр|Төрөл|Տեսակ|סוג|تىپى|جۆر|نوع|ٹایِپ|ډول|टंकलेखन करा|टाइप|प्रकार|रोखोम|ধরন|প্রকার|প্ৰকাৰ|ਟਾਈਪ|પ્રકાર|ପ୍ରକାର|வகை|రకం|ಪ್ರಕಾರ|തരം|වර්ගය|ประเภท|အမျိုးအစား|ტიპი|አይነት|ប្រភេទ|タイプ|类型|類型|형식)$");
enum OperatingSystem { linux, macos, windows }
Map<OperatingSystem, String> osNames = {
OperatingSystem.linux: 'Linux',
OperatingSystem.macos: 'macOS',
OperatingSystem.windows: 'Windows',
};
class BrowseItem {
String type, name, path, uri;
BrowseItem(
this.type,
this.name,
this.path,
this.uri,
);
BrowseItem.fromUrl(String url)
: uri = url.startsWith(urlRegExp) ? url : 'https://$url',
type = 'web',
path = '',
name = '';
/// Sending a directory: url when enqueueing makes a directory display as directory in the VLC
/// playlist instead of as a generic file.
String get playlistUri {
if (isDir) return uri.replaceAll(RegExp(r'^file'), 'directory');
return uri;
}
IconData get icon {
if (isDir) {
return Icons.folder;
}
if (isWeb) {
return Icons.public;
}
if (isAudio) {
return Icons.audiotrack;
}
if (isVideo) {
return Icons.movie;
}
if (isPlaylist) {
return Icons.list;
}
return Icons.insert_drive_file;
}
bool get isAudio => _audioExtensions.hasMatch(path);
bool get isDir => type == 'dir';
bool get isFile => type == 'file';
bool get isPlaylist => _playlistExtensions.hasMatch(path);
bool get isSupportedMedia => isAudio || isVideo || isWeb;
bool get isVideo => _videoExtensions.hasMatch(path);
bool get isWeb => type == 'web';
String get title => isVideo ? cleanVideoTitle(name, keepExt: isFile) : name;
BrowseItem.fromJson(Map<String, dynamic> json)
: type = json['type'],
name = json['name'],
path = json['path'],
uri = json['uri'];
Map<String, dynamic> toJson() => {
'type': type,
'name': name,
'path': path,
'uri': uri,
};
@override
String toString() => 'BrowseItem(${toJson()})';
}
enum BrowseResultIntent { play, enqueue }
class BrowseResult {
BrowseItem item;
BrowseResultIntent intent;
BrowseResult(this.item, this.intent);
}
// ignore: unused_element
const _emulatorLocalhost = '10.0.2.2';
const defaultPort = '8080';
const defaultPassword = 'vlcplayer';
var _ipPattern = RegExp(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$');
var _numericPattern = RegExp(r'^\d+$');
class Connection {
late String _ip = '';
late String _port = defaultPort;
late String _password = defaultPassword;
String? _ipError;
String? _portError;
String? _passwordError;
Connection();
String get ip => _ip;
String get port => _port;
String get password => _password;
get ipError => _ipError;
get portError => _portError;
get passwordError => _passwordError;
String get authority => '$_ip:$_port';
/// The connection stored in [Settings] will only have an IP if it's been
/// successfully tested.
bool get hasIp => _ip.isNotEmpty;
bool get isValid =>
_ipError == null && _portError == null && _passwordError == null;
bool get isNotValid => !isValid;
set ip(String value) {
if (value.trim().isEmpty) {
_ipError = 'An IP address is required';
} else if (!_ipPattern.hasMatch(value)) {
_ipError = 'Must have 4 parts separated by periods';
} else {
_ipError = null;
}
_ip = value;
}
set port(String value) {
_port = value;
if (value.trim().isEmpty) {
_portError = 'A port number is required';
} else if (!_numericPattern.hasMatch(value)) {
_portError = 'Must be all digits';
} else {
_portError = null;
}
_port = value;
}
set password(String value) {
if (value.trim().isEmpty) {
_passwordError = 'A password is required';
} else {
_passwordError = null;
}
_password = value;
}
Connection.fromJson(Map<String, dynamic> json) {
ip = json['ip'] ?? '';
port = json['port'] ?? defaultPort;
password = json['password'] ?? defaultPassword;
}
Map<String, dynamic> toJson() => {
'ip': ip,
'port': port,
'password': password,
};
}
class Settings {
final SharedPreferences _prefs;
late bool blurredCoverBg;
late bool dense;
late Connection connection;
Settings(this._prefs) {
Map<String, dynamic> json =
jsonDecode(_prefs.getString('settings') ?? '{}');
blurredCoverBg = json['blurredCoverBg'] ?? true;
connection = Connection.fromJson(json['connection'] ?? {});
dense = json['dense'] ?? false;
}
Map<String, dynamic> toJson() => {
'blurredCoverBg': blurredCoverBg,
'connection': connection,
'dense': dense,
};
save() {
_prefs.setString('settings', jsonEncode(this));
}
}
class LanguageTrack {
String name;
int streamNumber;
LanguageTrack(this.name, this.streamNumber);
@override
String toString() {
return '$name ($streamNumber)';
}
}
class Equalizer {
late bool enabled;
late List<Preset> presets;
late List<Band> bands;
late double preamp;
@override
String toString() {
if (!enabled) {
return 'Equalizer(off)';
}
return 'Equalizer(preamp: ${preamp.toStringAsFixed(1)}, bands: ${bands.map((b) => b.value.toStringAsFixed(1)).join(', ')})';
}
}
class Band {
int id;
double value;
Band(this.id, this.value);
}
class Preset {
int id;
String name;
Preset(this.id, this.name);
}
String findFirstElementText(xml.XmlDocument document, String name,
[String fallback = '']) {
var elements = document.findAllElements(name);
if (elements.isNotEmpty) {
return elements.first.text;
}
return fallback;
}
String findFirstChildElementText(xml.XmlElement element, String name,
[String fallback = '']) {
var elements = element.findElements(name);
if (elements.isNotEmpty) {
return elements.first.text;
}
return fallback;
}
class VlcStatusResponse {
xml.XmlDocument document;
List<LanguageTrack>? _audioTracks;
List<LanguageTrack>? _subtitleTracks;
Map<String, String>? _info;
VlcStatusResponse(this.document);
String get state => findFirstElementText(document, 'state');
Duration get time =>
Duration(seconds: int.parse(findFirstElementText(document, 'time', '0')));
Duration get length => Duration(
seconds: int.parse(findFirstElementText(document, 'length', '0')));
int get volume {
return int.parse(findFirstElementText(document, 'volume', '256'));
}
double get rate => double.parse(document.findAllElements('rate').first.text);
Map<String, String> get _metadata {
if (_info == null) {
xml.XmlElement? category;
var informations = document.rootElement.findElements('information');
if (informations.isNotEmpty) {
var categories = informations.first.findElements('category');
if (categories.isNotEmpty) {
category = categories.first;
}
}
_info = category != null
? {
for (var el in category.findElements('info'))
el.getAttribute('name') ?? '': el.text
}
: {};
}
return _info!;
}
String get title => _metadata['title'] ?? _metadata['filename'] ?? '';
String get artist => _metadata['artist'] ?? '';
String get artworkUrl => _metadata['artwork_url'] ?? '';
bool get fullscreen => findFirstElementText(document, 'fullscreen') == 'true';
bool get repeat => findFirstElementText(document, 'repeat') == 'true';
bool get random => findFirstElementText(document, 'random') == 'true';
bool get loop => findFirstElementText(document, 'loop') == 'true';
String get currentPlId => findFirstElementText(document, 'currentplid', '-1');
String get version => findFirstElementText(document, 'version');
List<LanguageTrack> get audioTracks {
return _audioTracks ??= _getLanguageTracks(_audioTranslations);
}
List<LanguageTrack> get subtitleTracks {
return _subtitleTracks ??= _getLanguageTracks(_subtitleTranslations);
}
Equalizer get equalizer {
var equalizer = Equalizer();
var el = document.rootElement.findElements('equalizer').first;
equalizer.enabled = el.firstChild != null;
if (!equalizer.enabled) {
return equalizer;
}
equalizer.presets = el
.findAllElements('preset')
.map((el) => Preset(
int.parse(el.getAttribute('id')!),
el.text,
))
.toList();
equalizer.presets.sort((a, b) => a.id - b.id);
equalizer.bands = el
.findAllElements('band')
.map((el) => Band(
int.parse(el.getAttribute('id')!),
double.parse(el.text),
))
.toList();
equalizer.bands.sort((a, b) => a.id - b.id);
equalizer.preamp = double.parse(el.findElements('preamp').first.text);
return equalizer;
}
List<LanguageTrack> _getLanguageTracks(RegExp type) {
List<LanguageTrack> tracks = [];
document.findAllElements('category').forEach((category) {
Map<String, String> info = {
for (var info in category.findElements('info'))
info.getAttribute('name')!: info.text
};
String? typeKey = firstWhereOrNull(
info.keys, (key) => _typeTranslations.hasMatch(key.trim()));
if (typeKey == null || !type.hasMatch(info[typeKey]!.trim())) {
return;
}
var streamName = category.getAttribute('name');
var streamNumber = int.tryParse(streamName!.split(' ').last);
if (streamNumber == null) {
return;
}
var codec = _getStreamInfoItem(info, _codecTranslations);
var description = _getStreamInfoItem(info, _descriptionTranslations);
var language = _getStreamInfoItem(info, _languageTranslations);
String name = streamName;
if (description != null && language != null) {
if (description.startsWith(language)) {
name = description;
} else {
name = '$description [$language]';
}
} else if (language != null) {
name = language;
} else if (description != null) {
name = description;
} else if (codec != null) {
name = codec;
}
tracks.add(LanguageTrack(name, streamNumber));
});
tracks.sort((a, b) => a.streamNumber - b.streamNumber);
return tracks;
}
String? _getStreamInfoItem(Map<String, String> info, RegExp name) {
String? key =
firstWhereOrNull(info.keys, (key) => name.hasMatch(key.trim()));
return (key != null && info[key]!.isNotEmpty) ? info[key] : null;
}
@override
String toString() {
return 'VlcStatusResponse(${{
'state': state,
'time': time,
'length': length,
'volume': volume,
'title': title,
'fullscreen': fullscreen,
'repeat': repeat,
'random': random,
'loop': loop,
'currentPlId': currentPlId,
'version': version,
'audioTracks': audioTracks,
'subtitleTracks': subtitleTracks,
}})';
}
}
class PlaylistItem {
String id;
String name;
String uri;
Duration duration;
bool current;
PlaylistItem.fromXmlElement(xml.XmlElement el)
: name = el.getAttribute('name')!,
id = el.getAttribute('id')!,
duration = Duration(seconds: int.parse(el.getAttribute('duration')!)),
uri = el.getAttribute('uri')!,
current = el.getAttribute('current') != null;
IconData get icon {
if (isDir) {
return Icons.folder;
}
if (isWeb) {
return Icons.public;
}
if (isAudio) {
return Icons.audiotrack;
}
if (isVideo) {
return Icons.movie;
}
return Icons.insert_drive_file;
}
bool get isAudio => _audioExtensions.hasMatch(uri);
bool get isDir => uri.startsWith('directory:');
bool get isFile => uri.startsWith('file:');
bool get isMedia => isAudio || isVideo || isWeb;
bool get isVideo => _videoExtensions.hasMatch(uri);
bool get isWeb => uri.startsWith('http');
String get title => isVideo ? cleanVideoTitle(name, keepExt: false) : name;
@override
String toString() {
return 'PlaylistItem(${{
'name': name,
'title': title,
'id': id,
'duration': duration,
'uri': uri,
'current': current
}})';
}
}
class VlcPlaylistResponse {
List<PlaylistItem> items;
PlaylistItem? currentItem;
VlcPlaylistResponse.fromXmlDocument(xml.XmlDocument doc)
: items = doc.rootElement
.findElements('node')
.first
.findAllElements('leaf')
.map((el) => PlaylistItem.fromXmlElement(el))
.toList() {
currentItem = firstWhereOrNull(items, (item) => item.current);
}
@override
String toString() {
return 'VlcPlaylistResponse(${{
'items': items,
'currentItem': currentItem
}})';
}
}
| 0 |
mirrored_repositories/remote_control_for_vlc | mirrored_repositories/remote_control_for_vlc/lib/main.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'models.dart';
import 'remote_control.dart';
/// Global access to the navigator state for showing an error dialog.
final GlobalKey<NavigatorState> navigatorKey =
GlobalKey(debugLabel: 'AppNavigator');
/// Flag to avoid showing multiple error dialogs.
var showingErrorDialog = false;
void main() async {
FlutterError.onError = (FlutterErrorDetails details) async {
Zone.current.handleUncaughtError(details.exception, details.stack!);
};
runZonedGuarded<Future<void>>(() async {
WidgetsFlutterBinding.ensureInitialized();
var prefs = await SharedPreferences.getInstance();
runApp(VlcRemote(prefs: prefs, settings: Settings(prefs)));
}, (error, stackTrace) async {
if (showingErrorDialog ||
navigatorKey.currentState?.overlay?.context == null) {
return;
}
showingErrorDialog = true;
await showDialog(
context: navigatorKey.currentState!.overlay!.context,
builder: (context) => AlertDialog(
title: const Text('Unhandled Error'),
content: SingleChildScrollView(
child: Column(
children: <Widget>[
Text('$error\n\n$stackTrace'),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('COPY ERROR DETAILS'),
onPressed: () {
Clipboard.setData(
ClipboardData(text: '$error\n\n$stackTrace'),
);
},
)
],
),
);
showingErrorDialog = false;
});
}
class VlcRemote extends StatelessWidget {
final SharedPreferences prefs;
final Settings settings;
const VlcRemote({
Key? key,
required this.prefs,
required this.settings,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
title: 'Remote Control for VLC',
theme: ThemeData(
primarySwatch: Colors.deepOrange,
),
home: RemoteControl(prefs: prefs, settings: settings),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store | mirrored_repositories/E-Commerce-Store/lib/app.dart | import 'package:ecommerce_store/bindings/general_bindings.dart';
import 'package:ecommerce_store/utils/constants/colors.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'utils/theme/theme.dart';
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'FlutterStore',
initialBinding: GeneralBindings(),
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.system,
theme: AppTheme.lightTheme,
darkTheme: AppTheme.darkTheme,
home: const Scaffold(backgroundColor: AppColors.primary, body: Center(child: CircularProgressIndicator(color: Colors.white))),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store | mirrored_repositories/E-Commerce-Store/lib/navigation_menu.dart | import 'package:ecommerce_store/features/personalization/screens/settings/settings.dart';
import 'package:ecommerce_store/features/shop/screens/home/home.dart';
import 'package:ecommerce_store/features/shop/screens/store/store.dart';
import 'package:ecommerce_store/features/shop/screens/wishlist/wishlist.dart';
import 'package:ecommerce_store/utils/constants/colors.dart';
import 'package:ecommerce_store/utils/helpers/helper_functions.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:iconsax/iconsax.dart';
class NavigationMenu extends StatelessWidget {
const NavigationMenu({super.key});
@override
Widget build(BuildContext context) {
final controller = Get.put(NavigationController());
final darkMode = HelperFunctions.isDarkMode(context);
return Scaffold(
bottomNavigationBar: Obx(
() => NavigationBar(
height: 70,
elevation: 0,
selectedIndex: controller.selectedIndex.value,
onDestinationSelected: (index) => controller.selectedIndex.value = index,
backgroundColor: darkMode ? AppColors.black : Colors.white,
indicatorColor: darkMode ? AppColors.white.withOpacity(0.1) : AppColors.black.withOpacity(0.1),
destinations: const [
NavigationDestination(icon: Icon(Iconsax.home), label: 'Home'),
NavigationDestination(icon: Icon(Iconsax.shop), label: 'Store'),
NavigationDestination(icon: Icon(Iconsax.heart), label: 'Wishlist'),
NavigationDestination(icon: Icon(Iconsax.user), label: 'Profile'),
],
),
),
body: Obx(() => controller.screens[controller.selectedIndex.value]),
);
}
}
class NavigationController extends GetxController {
final Rx<int> selectedIndex = 0.obs;
final screens = [
const HomeScreen(),
const StoreScreen(),
const FavoriteScreen(),
const SettingsScreen(),
];
}
| 0 |
mirrored_repositories/E-Commerce-Store | mirrored_repositories/E-Commerce-Store/lib/main.dart | import 'package:ecommerce_store/app.dart';
import 'package:ecommerce_store/data/repositories/authentication/authentication_repository.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'firebase_options.dart';
Future<void> main() async {
final WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
await GetStorage.init();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform).then((value) => Get.put(AuthenticationRepository()));
runApp(const App());
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/personalization | mirrored_repositories/E-Commerce-Store/lib/features/personalization/controllers/user_controller.dart | import 'package:ecommerce_store/data/repositories/user/user_repository.dart';
import 'package:ecommerce_store/features/authentication/models/user_model.dart';
import 'package:ecommerce_store/utils/popups/loaders.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:get/get.dart';
class UserController extends GetxController {
static UserController get instance => Get.find();
final userRepository = Get.put(UserRepository());
Future<void> saveUserRecord(UserCredential? userCredentials) async {
try {
if (userCredentials != null) {
final nameParts = UserModel.nameParts(userCredentials.user!.displayName ?? '');
final username = UserModel.generateUsername(userCredentials.user!.displayName ?? '');
final user = UserModel(
id: userCredentials.user!.uid,
firstName: nameParts[0],
lastName: nameParts.length > 1 ? nameParts.sublist(1).join(' ') : '',
username: username,
email: userCredentials.user!.email ?? '',
phoneNumber: userCredentials.user!.phoneNumber ?? '',
profilePicture: userCredentials.user!.photoURL ?? '',
);
await userRepository.saveUserRecord(user);
}
} catch (e) {
Loaders.warningSnackBar(title: 'Data not saved', message: 'Something went wrong while saving your information. You can re-save your data in your Profile.');
}
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens | mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens/profile/profile.dart | import 'package:ecommerce_store/common/widgets/appbar/appbar.dart';
import 'package:ecommerce_store/common/widgets/images/circular_image.dart';
import 'package:ecommerce_store/common/widgets/texts/section_heading.dart';
import 'package:ecommerce_store/utils/constants/image_strings.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import 'package:iconsax/iconsax.dart';
import 'widgets/profile_menu.dart';
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar(
title: Text('Profile'),
showBackArrow: true,
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(Sizes.defaultSpace),
child: Column(
children: [
SizedBox(
width: double.infinity,
child: Column(
children: [
const CircularImage(image: ImageStrings.user, width: 80, height: 80),
TextButton(onPressed: () {}, child: const Text('Change Profile Picture')),
],
),
),
const SizedBox(height: Sizes.spaceBtwItems / 2),
const Divider(),
const SizedBox(height: Sizes.spaceBtwItems),
const SectionHeading(title: 'Profile Information', showActionButton: false),
const SizedBox(height: Sizes.spaceBtwItems),
ProfileMenu(title: 'Name', value: 'Jan Kowalski', onPressed: () {}),
ProfileMenu(title: 'Username', value: 'jan_kowalski', onPressed: () {}),
const SizedBox(height: Sizes.spaceBtwItems),
const Divider(),
const SizedBox(height: Sizes.spaceBtwItems),
const SectionHeading(title: 'Personal Information', showActionButton: false),
const SizedBox(height: Sizes.spaceBtwItems),
ProfileMenu(onPressed: () {}, title: 'User ID', value: '45689', icon: Iconsax.copy),
ProfileMenu(onPressed: () {}, title: 'E-mail', value: 'jan.kowalski'),
ProfileMenu(onPressed: () {}, title: 'Phone Number', value: '+48 123 123 123'),
ProfileMenu(onPressed: () {}, title: 'Gender', value: 'Male'),
ProfileMenu(onPressed: () {}, title: 'Date of Birth', value: '28 Jan, 2002'),
const Divider(),
const SizedBox(height: Sizes.spaceBtwItems),
Center(
child: TextButton(
onPressed: () {},
child: const Text('Close Account', style: TextStyle(color: Colors.red)),
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens/profile | mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens/profile/widgets/profile_menu.dart | import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import 'package:iconsax/iconsax.dart';
class ProfileMenu extends StatelessWidget {
const ProfileMenu({
super.key,
this.icon = Iconsax.arrow_right_34,
required this.onPressed,
required this.title,
required this.value,
});
final IconData icon;
final VoidCallback onPressed;
final String title, value;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPressed,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: Sizes.spaceBtwItems / 1.5),
child: Row(
children: [
Expanded(flex: 3, child: Text(title, style: Theme.of(context).textTheme.bodySmall, overflow: TextOverflow.ellipsis)),
Expanded(
flex: 5,
child: Text(value, style: Theme.of(context).textTheme.bodyMedium, overflow: TextOverflow.ellipsis),
),
Expanded(child: Icon(icon, size: 18)),
],
),
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens | mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens/settings/settings.dart | import 'package:ecommerce_store/common/widgets/appbar/appbar.dart';
import 'package:ecommerce_store/common/widgets/custom_shapes/containers/primary_header_container.dart';
import 'package:ecommerce_store/common/widgets/list_tiles/settings_menu_tile.dart';
import 'package:ecommerce_store/common/widgets/texts/section_heading.dart';
import 'package:ecommerce_store/features/personalization/screens/address/address.dart';
import 'package:ecommerce_store/features/shop/screens/cart/cart.dart';
import 'package:ecommerce_store/features/shop/screens/order/order.dart';
import 'package:ecommerce_store/utils/constants/colors.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:iconsax/iconsax.dart';
import '../../../../common/widgets/list_tiles/user_profile_tile.dart';
import '../../../../data/repositories/authentication/authentication_repository.dart';
import '../profile/profile.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
PrimaryHeaderContainer(
child: Column(
children: [
CustomAppBar(
title: Text('Account', style: Theme.of(context).textTheme.headlineMedium!.apply(color: AppColors.white)),
),
UserProfileTile(onPressed: () => Get.to(() => const ProfileScreen())),
const SizedBox(height: Sizes.spaceBtwSections),
],
),
),
Padding(
padding: const EdgeInsets.all(Sizes.defaultSpace),
child: Column(
children: [
const SectionHeading(title: 'Account Settings', showActionButton: false),
const SizedBox(height: Sizes.spaceBtwItems),
SettingsMenuTile(
icon: Iconsax.safe_home,
title: 'My Addresses',
subTitle: 'Set shopping delivery address',
onTap: () => Get.to(() => const UserAddressScreen()),
),
SettingsMenuTile(
icon: Iconsax.shopping_cart,
title: 'My Cart',
subTitle: 'Add, remove products and move to checkout',
onTap: () => Get.to(() => const CartScreen()),
),
SettingsMenuTile(
icon: Iconsax.bag_tick,
title: 'My Orders',
subTitle: 'In-progress and Completed Orders',
onTap: () => Get.to(() => const OrderScreen()),
),
const SettingsMenuTile(icon: Iconsax.bank, title: 'Bank Account', subTitle: 'Withdraw balance to registered bank account'),
const SettingsMenuTile(icon: Iconsax.discount_shape, title: 'My Coupons', subTitle: 'List of all the discounted coupons'),
const SettingsMenuTile(icon: Iconsax.notification, title: 'Notifications', subTitle: 'Set any kind of notification message'),
const SettingsMenuTile(icon: Iconsax.security_card, title: 'Account Privacy', subTitle: 'Manage data usage and connected accounts'),
const SizedBox(height: Sizes.spaceBtwSections),
const SectionHeading(title: 'App Settings', showActionButton: false),
const SizedBox(height: Sizes.spaceBtwItems),
const SettingsMenuTile(icon: Iconsax.document_upload, title: 'Load Data', subTitle: 'Upload Data to your Cloud Firebase'),
SettingsMenuTile(
icon: Iconsax.location,
title: 'Geolocation',
subTitle: 'Set recommendation based on location',
trailing: Switch(value: true, onChanged: (value) {}),
),
SettingsMenuTile(
icon: Iconsax.location,
title: 'Safe Mode',
subTitle: 'Search result is safe for all ages',
trailing: Switch(value: false, onChanged: (value) {}),
),
SettingsMenuTile(
icon: Iconsax.location,
title: 'HD Image Quality',
subTitle: 'Set image quality to be seen',
trailing: Switch(value: false, onChanged: (value) {}),
),
const SizedBox(height: Sizes.spaceBtwSections),
SizedBox(
width: double.infinity,
child: OutlinedButton(onPressed: () => AuthenticationRepository.instance.logout(), child: const Text('Logout')),
),
const SizedBox(height: Sizes.spaceBtwSections * 2.5),
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens | mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens/address/address.dart | import 'package:ecommerce_store/common/widgets/appbar/appbar.dart';
import 'package:ecommerce_store/features/personalization/screens/address/add_new_address.dart';
import 'package:ecommerce_store/features/personalization/screens/address/widgets/single_address.dart';
import 'package:ecommerce_store/utils/constants/colors.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:iconsax/iconsax.dart';
class UserAddressScreen extends StatelessWidget {
const UserAddressScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () => Get.to(() => const AddNewAddressScreen()),
backgroundColor: AppColors.primary,
child: const Icon(Iconsax.add, color: AppColors.white),
),
appBar: CustomAppBar(showBackArrow: true, title: Text('Addresses', style: Theme.of(context).textTheme.headlineSmall)),
body: const SingleChildScrollView(
padding: EdgeInsets.all(Sizes.defaultSpace),
child: Column(
children: [
SingleAddress(selectedAddress: true),
SingleAddress(selectedAddress: false),
],
),
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens | mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens/address/add_new_address.dart | import 'package:ecommerce_store/common/widgets/appbar/appbar.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import 'package:iconsax/iconsax.dart';
class AddNewAddressScreen extends StatelessWidget {
const AddNewAddressScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar(showBackArrow: true, title: Text('Add new Address')),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(Sizes.defaultSpace),
child: Form(
child: Column(
children: [
TextFormField(decoration: const InputDecoration(prefixIcon: Icon(Iconsax.user), labelText: 'Name')),
const SizedBox(height: Sizes.spaceBtwInputFields),
TextFormField(decoration: const InputDecoration(prefixIcon: Icon(Iconsax.mobile), labelText: 'Phone Number')),
const SizedBox(height: Sizes.spaceBtwInputFields),
Row(
children: [
Expanded(
child: TextFormField(decoration: const InputDecoration(prefixIcon: Icon(Iconsax.building_31), labelText: 'Street')),
),
const SizedBox(width: Sizes.spaceBtwInputFields),
Expanded(
child: TextFormField(decoration: const InputDecoration(prefixIcon: Icon(Iconsax.code), labelText: 'Postal Code')),
),
],
),
const SizedBox(height: Sizes.spaceBtwInputFields),
Row(
children: [
Expanded(
child: TextFormField(decoration: const InputDecoration(prefixIcon: Icon(Iconsax.building), labelText: 'City')),
),
const SizedBox(width: Sizes.spaceBtwInputFields),
Expanded(
child: TextFormField(decoration: const InputDecoration(prefixIcon: Icon(Iconsax.activity), labelText: 'State')),
),
],
),
const SizedBox(height: Sizes.spaceBtwInputFields),
TextFormField(decoration: const InputDecoration(prefixIcon: Icon(Iconsax.global), labelText: 'Country')),
const SizedBox(height: Sizes.defaultSpace),
SizedBox(width: double.infinity, child: ElevatedButton(onPressed: () {}, child: const Text('Save'))),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens/address | mirrored_repositories/E-Commerce-Store/lib/features/personalization/screens/address/widgets/single_address.dart | import 'package:ecommerce_store/utils/constants/colors.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:ecommerce_store/utils/helpers/helper_functions.dart';
import 'package:flutter/material.dart';
import 'package:iconsax/iconsax.dart';
import '../../../../../common/widgets/custom_shapes/containers/rounded_container.dart';
class SingleAddress extends StatelessWidget {
const SingleAddress({super.key, required this.selectedAddress});
final bool selectedAddress;
@override
Widget build(BuildContext context) {
final dark = HelperFunctions.isDarkMode(context);
return RoundedContainer(
padding: const EdgeInsets.all(Sizes.md),
width: double.infinity,
showBorder: true,
backgroundColor: selectedAddress ? AppColors.primary.withOpacity(0.5) : Colors.transparent,
borderColor: selectedAddress
? Colors.transparent
: dark
? AppColors.darkerGrey
: AppColors.grey,
margin: const EdgeInsets.only(bottom: Sizes.spaceBtwItems),
child: Stack(
children: [
Positioned(
right: 5,
top: 0,
child: Icon(
selectedAddress ? Iconsax.tick_circle5 : null,
color: selectedAddress
? dark
? AppColors.light
: AppColors.dark
: null,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'John Doe',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: Sizes.sm / 2),
const Text('(+123) 456 789 012', maxLines: 1, overflow: TextOverflow.ellipsis),
const SizedBox(height: Sizes.sm / 2),
const Text('82356 Timmy Coves, South Liana, Maine, 87665, USA', softWrap: true),
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop | mirrored_repositories/E-Commerce-Store/lib/features/shop/controllers/home_controller.dart | import 'package:get/get.dart';
class HomeController extends GetxController {
static HomeController get instance => Get.find();
final carouselCurrentIndex = 0.obs;
void updatePageIndicator(index) {
carouselCurrentIndex.value = index;
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop/screens | mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/product_reviews/product_reviews.dart | import 'package:ecommerce_store/common/widgets/appbar/appbar.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import '../../../../common/widgets/products/ratings/rating_indicator.dart';
import 'widgets/rating_progress_indicator.dart';
import 'widgets/user_review_card.dart';
class ProductReviewsScreen extends StatelessWidget {
const ProductReviewsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar(title: Text('Reviews & Ratings'), showBackArrow: true),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(Sizes.defaultSpace),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Ratings and reviews are verified and are from people who use the same type of device that you use.'),
const SizedBox(height: Sizes.spaceBtwItems),
const OverallProductRating(),
const CustomRatingBarIndicator(rating: 4.5),
Text('12, 611', style: Theme.of(context).textTheme.bodySmall),
const SizedBox(height: Sizes.spaceBtwSections),
const UserReviewCard(),
const UserReviewCard(),
const UserReviewCard(),
const UserReviewCard(),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/product_reviews | mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/product_reviews/widgets/rating_progress_indicator.dart | import 'package:flutter/material.dart';
import 'progress_indicator_and_rating.dart';
class OverallProductRating extends StatelessWidget {
const OverallProductRating({
super.key,
});
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(flex: 3, child: Text('4.8', style: Theme.of(context).textTheme.displayLarge)),
const Expanded(
flex: 7,
child: Column(
children: [
RatingProgressIndicator(text: '5', value: 1.0),
RatingProgressIndicator(text: '4', value: 0.8),
RatingProgressIndicator(text: '3', value: 0.6),
RatingProgressIndicator(text: '2', value: 0.4),
RatingProgressIndicator(text: '1', value: 0.2),
],
),
),
],
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/product_reviews | mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/product_reviews/widgets/progress_indicator_and_rating.dart | import 'package:flutter/material.dart';
import '../../../../../utils/constants/colors.dart';
import '../../../../../utils/device/device_utility.dart';
class RatingProgressIndicator extends StatelessWidget {
const RatingProgressIndicator({
super.key,
required this.text,
required this.value,
});
final String text;
final double value;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(flex: 1, child: Text(text, style: Theme.of(context).textTheme.bodyMedium)),
Expanded(
flex: 11,
child: SizedBox(
width: DeviceUtils.getScreenWidth(context) * 0.5,
child: LinearProgressIndicator(
value: value,
minHeight: 11,
backgroundColor: AppColors.grey,
valueColor: const AlwaysStoppedAnimation(AppColors.primary),
borderRadius: BorderRadius.circular(7),
),
),
),
],
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/product_reviews | mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/product_reviews/widgets/user_review_card.dart | import 'package:ecommerce_store/common/widgets/custom_shapes/containers/rounded_container.dart';
import 'package:ecommerce_store/common/widgets/products/ratings/rating_indicator.dart';
import 'package:ecommerce_store/utils/constants/colors.dart';
import 'package:ecommerce_store/utils/constants/image_strings.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:ecommerce_store/utils/helpers/helper_functions.dart';
import 'package:flutter/material.dart';
import 'package:readmore/readmore.dart';
class UserReviewCard extends StatelessWidget {
const UserReviewCard({super.key});
@override
Widget build(BuildContext context) {
final dark = HelperFunctions.isDarkMode(context);
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
const CircleAvatar(backgroundImage: AssetImage(ImageStrings.userProfileImage1)),
const SizedBox(width: Sizes.spaceBtwItems),
Text('John Doe', style: Theme.of(context).textTheme.titleLarge),
],
),
IconButton(onPressed: () {}, icon: const Icon(Icons.more_vert)),
],
),
const SizedBox(height: Sizes.spaceBtwItems),
Row(
children: [
const CustomRatingBarIndicator(rating: 4),
const SizedBox(width: Sizes.spaceBtwItems),
Text('01 Nov, 2023', style: Theme.of(context).textTheme.bodyMedium),
],
),
const SizedBox(height: Sizes.spaceBtwItems),
const ReadMoreText(
'The user interface of the app is quite intuitive. I was able to navigate and make purchases seamlessly. Great job!!',
trimLines: 2,
trimExpandedText: ' show less',
trimCollapsedText: ' show more',
trimMode: TrimMode.Line,
moreStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppColors.primary),
lessStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppColors.primary),
),
const SizedBox(height: Sizes.spaceBtwItems),
RoundedContainer(
backgroundColor: dark ? AppColors.darkerGrey : AppColors.grey,
child: Padding(
padding: const EdgeInsets.all(Sizes.md),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Flutter Store', style: Theme.of(context).textTheme.titleMedium),
Text('02 Nov, 2023', style: Theme.of(context).textTheme.bodyMedium),
],
),
const SizedBox(height: Sizes.spaceBtwItems),
const ReadMoreText(
'The user interface of the app is quite intuitive. I was able to navigate and make purchases seamlessly. Great job!!',
trimLines: 2,
trimExpandedText: ' show less',
trimCollapsedText: ' show more',
trimMode: TrimMode.Line,
moreStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppColors.primary),
lessStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppColors.primary),
),
],
),
),
),
const SizedBox(height: Sizes.spaceBtwSections),
],
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop/screens | mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/cart/cart.dart | import 'package:ecommerce_store/common/widgets/appbar/appbar.dart';
import 'package:ecommerce_store/features/shop/screens/checkout/checkout.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'widgets/cart_items.dart';
class CartScreen extends StatelessWidget {
const CartScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppBar(title: Text('Cart', style: Theme.of(context).textTheme.headlineSmall), showBackArrow: true),
body: const Padding(
padding: EdgeInsets.all(Sizes.defaultSpace),
child: CartItems(),
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.all(Sizes.defaultSpace),
child: ElevatedButton(onPressed: () => Get.to(() => const CheckoutScreen()), child: const Text('Checkout \$256')),
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/cart | mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/cart/widgets/cart_items.dart | import 'package:flutter/material.dart';
import '../../../../../common/widgets/products/cart/add_remove_button.dart';
import '../../../../../common/widgets/products/cart/cart_item.dart';
import '../../../../../common/widgets/texts/product_price_text.dart';
import '../../../../../utils/constants/sizes.dart';
class CartItems extends StatelessWidget {
const CartItems({
super.key,
this.showAddRemoveButtons = true,
});
final bool showAddRemoveButtons;
@override
Widget build(BuildContext context) {
return ListView.separated(
shrinkWrap: true,
separatorBuilder: (_, __) => const SizedBox(height: Sizes.spaceBtwSections),
itemCount: 2,
itemBuilder: (_, index) => Column(
children: [
const CartItem(),
if (showAddRemoveButtons) const SizedBox(height: Sizes.spaceBtwItems),
if (showAddRemoveButtons)
const Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
SizedBox(width: 70),
ProductQuantityWithAddRemoveButton(),
],
),
ProductPriceText(price: '256'),
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop/screens | mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/wishlist/wishlist.dart | import 'package:ecommerce_store/common/widgets/appbar/appbar.dart';
import 'package:ecommerce_store/common/widgets/icons/circular_icon.dart';
import 'package:ecommerce_store/common/widgets/layouts/grid_layout.dart';
import 'package:ecommerce_store/common/widgets/products/product_cards/product_card_vertical.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:iconsax/iconsax.dart';
import '../../../../navigation_menu.dart';
class FavoriteScreen extends StatelessWidget {
const FavoriteScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppBar(
title: Text('Wishlist', style: Theme.of(context).textTheme.headlineMedium),
actions: [
CircularIcon(
icon: Iconsax.add,
onPressed: () => Get.offAll(() => const NavigationMenu()),
),
],
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(Sizes.defaultSpace),
child: Column(
children: [
GridLayout(itemCount: 6, itemBuilder: (_, index) => const ProductCardVertical()),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop/screens | mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/sub_category/sub_categories.dart | import 'package:ecommerce_store/common/widgets/appbar/appbar.dart';
import 'package:ecommerce_store/common/widgets/images/rounded_image.dart';
import 'package:ecommerce_store/common/widgets/products/product_cards/product_card_horizontal.dart';
import 'package:ecommerce_store/common/widgets/texts/section_heading.dart';
import 'package:ecommerce_store/utils/constants/image_strings.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
class SubCategoriesScreen extends StatelessWidget {
const SubCategoriesScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar(title: Text('Sports shirts'), showBackArrow: true),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(Sizes.defaultSpace),
child: Column(
children: [
const RoundedImage(imageUrl: ImageStrings.promoBanner1, applyImageRadius: true, width: double.infinity),
const SizedBox(height: Sizes.spaceBtwSections),
Column(
children: [
SectionHeading(title: 'Sports shirts', onPressed: () {}),
const SizedBox(height: Sizes.spaceBtwItems / 2),
SizedBox(
height: 120,
child: ListView.separated(
itemCount: 4,
separatorBuilder: (context, index) => const SizedBox(width: Sizes.spaceBtwItems),
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => const ProductCardHorizontal(),
),
),
],
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/E-Commerce-Store/lib/features/shop/screens | mirrored_repositories/E-Commerce-Store/lib/features/shop/screens/all_products/all_products.dart | import 'package:ecommerce_store/common/widgets/appbar/appbar.dart';
import 'package:ecommerce_store/utils/constants/sizes.dart';
import 'package:flutter/material.dart';
import '../../../../common/widgets/products/sortable/sortable_products.dart';
class AllProducts extends StatelessWidget {
const AllProducts({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
appBar: CustomAppBar(title: Text('Popular Products'), showBackArrow: true),
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(Sizes.defaultSpace),
child: SortableProducts(),
),
),
);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.