repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/BMI-Flutter | mirrored_repositories/BMI-Flutter/lib/main.dart | import 'package:flutter/material.dart';
import 'input_page.dart';
void main() => runApp(const BMICalculator());
class BMICalculator extends StatelessWidget {
const BMICalculator({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: const Color(0xFF0A0E21),
colorScheme: const ColorScheme.light(primary: Color(0xFF0A0E21)),
),
home: const InputPage(),
);
}
}
| 0 |
mirrored_repositories/BMI-Flutter | mirrored_repositories/BMI-Flutter/lib/icon_content.dart | import 'package:flutter/material.dart';
class IconColumn extends StatelessWidget {
final IconData? icon;
final String? containerText;
const IconColumn({
this.icon,
this.containerText,
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
icon,
size: 80.0,
),
const SizedBox(
height: 15.0,
),
Text(
containerText!,
style: const TextStyle(
fontSize: 18.0,
color: Color(0xff8d8e98),
),
),
],
);
}
}
| 0 |
mirrored_repositories/BMI-Flutter | mirrored_repositories/BMI-Flutter/lib/reusable_card.dart | import 'package:flutter/material.dart';
class ReusableCard extends StatelessWidget {
final Color color;
final Widget? cardChild;
final VoidCallback? onPress;
const ReusableCard(
{Key? key, required this.color, this.cardChild, this.onPress})
: super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPress,
child: Container(
child: cardChild,
margin: const EdgeInsets.all(15.0),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(10.0),
),
),
);
}
}
| 0 |
mirrored_repositories/BMI-Flutter | mirrored_repositories/BMI-Flutter/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:BMI/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(BMICalculator());
// 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/sonic | mirrored_repositories/sonic/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:sonic/routes/navigation_routes.dart';
import 'package:sonic/src/screens/permission/permission.dart';
import 'package:flex_color_scheme/flex_color_scheme.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
//Icon( Icons.radar_outlined, ),
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MediaQuery(
data: MediaQueryData.fromWindow(WidgetsBinding.instance.window),
child: ScreenUtilInit(
designSize: const Size(500, 500),
minTextAdapt: true,
splitScreenMode: true,
builder: (context, child) => GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'Sonic',
theme: FlexThemeData.light(scheme: FlexScheme.aquaBlue),
// The Mandy red, dark theme.
darkTheme: FlexThemeData.dark(scheme: FlexScheme.aquaBlue),
themeMode: ThemeMode.system,
routes: routes,
initialRoute: PermissionsPage.routeName,
),
),
);
}
}
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/routes/navigation_routes.dart | import 'package:flutter/cupertino.dart';
import 'package:sonic/src/screens/bluetooth_off/bluetooth_off.dart';
import 'package:sonic/src/screens/device/devices.dart';
import 'package:sonic/src/screens/find_device/find_device.dart';
import 'package:sonic/src/screens/permission/permission.dart';
import '../src/screens/chats/chats.dart';
import '../src/screens/home/home.dart';
import '../src/screens/radar/radar.dart';
final Map<String, WidgetBuilder> routes = {
Home.routeName: (context) => Home(),
DeviceScreen.routeName: (context) => DeviceScreen(),
FindDevicesScreen.routeName: (context) => FindDevicesScreen(),
BluetoothOffScreen.routeName: (context) => const BluetoothOffScreen(),
PermissionsPage.routeName: (context) => PermissionsPage(),
ChatPage.routeName: (context) => const ChatPage(),
RadarView.routeName: (context) => const RadarView(),
};
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/components/custom_button.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class CustomButton extends StatelessWidget {
final String buttonText;
final Color buttonColor;
final Color textColor;
final bool? leading;
final VoidCallback onTap;
const CustomButton(
{Key? key,
required this.buttonText,
required this.buttonColor,
required this.textColor,
this.leading,
required this.onTap})
: super(key: key);
@override
Widget build(BuildContext context) {
return // Figma Flutter Generator Sign_buttonWidget - INSTANCE
InkWell(
onTap: onTap,
child: Container(
width: 315,
height: 58,
decoration: BoxDecoration(
color: buttonColor,
borderRadius: BorderRadius.circular(12),
boxShadow: const [
BoxShadow(
color: Color.fromRGBO(15, 218, 136, 0.3),
offset: Offset(0, 2),
blurRadius: 4)
],
),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
buttonText,
textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.headlineMedium!
.copyWith(color: textColor, fontSize: 20.w),
),
SizedBox(
width: 5.h,
),
leading == true
? Icon(
FontAwesomeIcons.arrowRight,
color: textColor,
size: 17,
)
: const SizedBox(),
],
),
)),
);
}
}
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/components/widgets.dart | // Copyright 2017, Paul DeMarco.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
class ScanResultTile extends StatelessWidget {
const ScanResultTile({Key? key, required this.result, required this.onTap})
: super(key: key);
final ScanResult result;
final VoidCallback onTap;
Widget _buildTitle(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
result.device.name,
overflow: TextOverflow.ellipsis,
),
Text(
result.device.id.toString(),
)
],
);
}
Widget _buildAdvRow(BuildContext context, String title, String value) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(title),
const SizedBox(
width: 12.0,
),
Expanded(
child: Text(
value,
),
),
],
),
);
}
String getNiceHexArray(List<int> bytes) {
return '[${bytes.map((i) => i.toRadixString(16).padLeft(2, '0')).join(', ')}]'
.toUpperCase();
}
String? getNiceManufacturerData(Map<int, List<int>> data) {
if (data.isEmpty) {
return null;
}
List<String> res = [];
data.forEach((id, bytes) {
res.add(
'${id.toRadixString(16).toUpperCase()}: ${getNiceHexArray(bytes)}');
});
return res.join(', ');
}
String? getNiceServiceData(Map<String, List<int>> data) {
if (data.isEmpty) {
return null;
}
List<String> res = [];
data.forEach((id, bytes) {
res.add('${id.toUpperCase()}: ${getNiceHexArray(bytes)}');
});
return res.join(', ');
}
@override
Widget build(BuildContext context) {
return ExpansionTile(
title: _buildTitle(context),
leading: Text(result.rssi.toString()),
trailing: ElevatedButton(
onPressed: (result.advertisementData.connectable) ? onTap : null,
child: const Text('CONNECT'),
),
children: <Widget>[
_buildAdvRow(
context, 'Complete Local Name', result.advertisementData.localName),
_buildAdvRow(context, 'Tx Power Level',
'${result.advertisementData.txPowerLevel ?? 'N/A'}'),
_buildAdvRow(
context,
'Manufacturer Data',
getNiceManufacturerData(
result.advertisementData.manufacturerData) ??
'N/A'),
_buildAdvRow(
context,
'Service UUIDs',
(result.advertisementData.serviceUuids.isNotEmpty)
? result.advertisementData.serviceUuids.join(', ').toUpperCase()
: 'N/A'),
_buildAdvRow(context, 'Service Data',
getNiceServiceData(result.advertisementData.serviceData) ?? 'N/A'),
],
);
}
}
class ServiceTile extends StatelessWidget {
final BluetoothService service;
final List<CharacteristicTile> characteristicTiles;
const ServiceTile(
{Key? key, required this.service, required this.characteristicTiles})
: super(key: key);
@override
Widget build(BuildContext context) {
if (characteristicTiles.isNotEmpty) {
return ExpansionTile(
title: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Text('Service'),
Text('0x${service.uuid.toString().toUpperCase().substring(4, 8)}'),
],
),
children: characteristicTiles,
);
} else {
return ListTile(
title: const Text('Service'),
subtitle:
Text('0x${service.uuid.toString().toUpperCase().substring(4, 8)}'),
);
}
}
}
class CharacteristicTile extends StatelessWidget {
final BluetoothCharacteristic characteristic;
final List<DescriptorTile> descriptorTiles;
final VoidCallback onReadPressed;
final VoidCallback onWritePressed;
final VoidCallback onNotificationPressed;
const CharacteristicTile(
{Key? key,
required this.characteristic,
required this.descriptorTiles,
required this.onReadPressed,
required this.onWritePressed,
required this.onNotificationPressed})
: super(key: key);
@override
Widget build(BuildContext context) {
return StreamBuilder<List<int>>(
stream: characteristic.value,
initialData: characteristic.lastValue,
builder: (c, snapshot) {
final value = snapshot.data;
return ExpansionTile(
title: ListTile(
title: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Text('Characteristic'),
Text(
'0x${characteristic.uuid.toString().toUpperCase().substring(4, 8)}'),
],
),
subtitle: Text(value.toString()),
contentPadding: const EdgeInsets.all(0.0),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(
Icons.file_download,
color: Theme.of(context).iconTheme.color!.withOpacity(0.5),
),
onPressed: onReadPressed,
),
IconButton(
icon: Icon(Icons.file_upload,
color: Theme.of(context).iconTheme.color!.withOpacity(0.5)),
onPressed: onWritePressed,
),
IconButton(
icon: Icon(
characteristic.isNotifying
? Icons.sync_disabled
: Icons.sync,
color: Theme.of(context).iconTheme.color!.withOpacity(0.5)),
onPressed: onNotificationPressed,
)
],
),
children: descriptorTiles,
);
},
);
}
}
class DescriptorTile extends StatelessWidget {
final BluetoothDescriptor descriptor;
final VoidCallback onReadPressed;
final VoidCallback onWritePressed;
const DescriptorTile(
{Key? key,
required this.descriptor,
required this.onReadPressed,
required this.onWritePressed})
: super(key: key);
@override
Widget build(BuildContext context) {
return ListTile(
title: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Text('Descriptor'),
Text('0x${descriptor.uuid.toString().toUpperCase().substring(4, 8)}')
],
),
subtitle: StreamBuilder<List<int>>(
stream: descriptor.value,
initialData: descriptor.lastValue,
builder: (c, snapshot) => Text(snapshot.data.toString()),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(
Icons.file_download,
color: Theme.of(context).iconTheme.color!.withOpacity(0.5),
),
onPressed: onReadPressed,
),
IconButton(
icon: Icon(
Icons.file_upload,
color: Theme.of(context).iconTheme.color!.withOpacity(0.5),
),
onPressed: onWritePressed,
)
],
),
);
}
}
class AdapterStateTile extends StatelessWidget {
const AdapterStateTile({Key? key, required this.state}) : super(key: key);
final BluetoothState state;
@override
Widget build(BuildContext context) {
return Container(
color: Colors.redAccent,
child: ListTile(
title: Text(
'Bluetooth adapter is ${state.toString().substring(15)}',
style: Theme.of(context).primaryTextTheme.bodySmall,
),
trailing: Icon(
Icons.error,
color: Theme.of(context).primaryTextTheme.bodySmall?.color,
),
),
);
}
}
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/model/data_model.dart |
class RadarData{
String distance;
String angle;
RadarData({required this.distance, required this.angle});
}
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/service/bluetooth.dart | // import 'dart:typed_data';
// import '../model/data_model.dart';
//
// void _onDataReceived(Uint8List data){
//
// List<RadarData> radarData = List<RadarData>.empty(growable: true);
// bool inProgress = false;
//
// _connection.input!.listen((data) {
// _buffer += data;
//
// while (true) {
// // If there is a sample, and it is full sent
// int index = _buffer.indexOf('.'.codeUnitAt(0));
// // if (index >= 0 && _buffer.length - index >= 7) {
// // final DataSample sample = DataSample(
// // temperature1: (_buffer[index + 1] + _buffer[index + 2] / 100),
// // temperature2: (_buffer[index + 3] + _buffer[index + 4] / 100),
// // waterpHlevel: (_buffer[index + 5] + _buffer[index + 6] / 100),
// // timestamp: DateTime.now());
// // _buffer.removeRange(0, index + 7);
// //
// // samples.add(sample);
// // notifyListeners(); // Note: It shouldn't be invoked very often - in this example data comes at every second, but if there would be more data, it should update (including repaint of graphs) in some fixed interval instead of after every sample.
// // //debugPrint("${sample.timestamp.toString()} -> ${sample.temperature1} / ${sample.temperature2}");
// // }
// // Otherwise break
// //angle min 15 to max 165
// //distance min 0 to max 2250
// //max length of message = 3angle + 4distance + 1comma = 8
// if(index >= 0 && _buffer.length - index >= 4){
// int separator = _buffer.indexOf(','.codeUnitAt(0));
// if(separator >= 0 && _buffer.length - separator >= 2){
// //print data
// String angle=String.fromCharCodes(_buffer.sublist(0,separator));
// String distance=String.fromCharCodes(_buffer.sublist(separator+1,index));
// final RadarData sample = RadarData(
// angle: angle,
// distance: distance,
// );
// radarData.add(sample);
// notifyListeners();
// //remove data from buffer
// }
// _buffer.removeRange(0, index + 1);
// }
// else {
// break;
// }
// }
// }).onDone(() {
// inProgress = false;
// notifyListeners();
// });
//
// }
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/bluetooth_off/bluetooth_off.dart | import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
class BluetoothOffScreen extends StatelessWidget {
static String routeName = '/bluetooth_off';
const BluetoothOffScreen({Key? key, this.state}) : super(key: key);
final BluetoothState? state;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightBlue,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Icon(
Icons.bluetooth_disabled,
size: 200.0,
color: Colors.white54,
),
Text(
'Bluetooth Adapter is ${state != null ? state.toString()
.substring(15) : 'not available'}.',
style: Theme
.of(context)
.primaryTextTheme
.bodyMedium,
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/device/devices.dart | import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';
import 'package:sonic/controller/device_controller.dart';
class DeviceScreen extends StatelessWidget {
static String routeName = '/device';
DeviceScreen({Key? key}) : super(key: key);
final BluetoothDevice device = Get.arguments as BluetoothDevice;
final DeviceController deviceControl = Get.put(DeviceController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(deviceControl.device.value.name),
actions: <Widget>[
StreamBuilder<BluetoothDeviceState>(
stream: deviceControl.device.value.state,
initialData: BluetoothDeviceState.connecting,
builder: (c, snapshot) {
VoidCallback onPressed;
String text;
switch (snapshot.data) {
case BluetoothDeviceState.connected:
onPressed = () => deviceControl.device.value.disconnect();
text = 'DISCONNECT';
break;
case BluetoothDeviceState.disconnected:
onPressed = () => deviceControl.device.value.connect();
text = 'CONNECT';
break;
default:
onPressed = () {};
text = snapshot.data.toString().substring(21).toUpperCase();
break;
}
return ElevatedButton(
onPressed: onPressed,
child: Text(
text,
));
},
)
],
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
StreamBuilder<BluetoothDeviceState>(
stream: deviceControl.device.value.state,
initialData: BluetoothDeviceState.connecting,
builder: (c, snapshot) => ListTile(
leading: (snapshot.data == BluetoothDeviceState.connected)
? const Icon(Icons.bluetooth_connected)
: const Icon(Icons.bluetooth_disabled),
title: Text(
'Device is ${snapshot.data.toString().split('.')[1]}.'),
subtitle: Text('${deviceControl.device.value.id}'),
trailing: StreamBuilder<bool>(
stream: deviceControl.device.value.isDiscoveringServices,
initialData: false,
builder: (c, snapshot) => IndexedStack(
index: snapshot.data! ? 1 : 0,
children: <Widget>[
IconButton(
icon: const Icon(Icons.refresh),
onPressed: () =>
deviceControl.device.value.discoverServices(),
),
const IconButton(
icon: SizedBox(
width: 18.0,
height: 18.0,
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.grey),
),
),
onPressed: null,
)
],
),
),
),
),
StreamBuilder<int>(
stream: deviceControl.device.value.mtu,
initialData: 0,
builder: (c, snapshot) => ListTile(
title: const Text('MTU Size'),
subtitle: Text('${snapshot.data} bytes'),
trailing: IconButton(
icon: const Icon(Icons.edit),
onPressed: () => deviceControl.device.value.requestMtu(223),
),
),
),
StreamBuilder<List<BluetoothService>>(
stream: deviceControl.device.value.services,
initialData: const [],
builder: (c, snapshot) {
return Column(
children: deviceControl.buildServiceTiles(
snapshot.data as List<BluetoothService>),
);
},
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/radar/radar.dart | import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../constant/constant.dart';
import '../../../controller/radar_controller.dart';
class RadarView extends StatefulWidget {
static const String routeName = '/radarView';
const RadarView({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _RadarViewState();
}
class _RadarViewState extends State<RadarView> {
late Timer timer;
double angle = 0;
double distance = 0;
final RadarController _controller =
Get.put(RadarController(address: Get.arguments as String));
@override
void initState() {
timer = Timer.periodic(const Duration(milliseconds: 30), (timer) {
setState(() {
angle = _controller.iangle.value;
distance = _controller.idistance.value;
});
});
super.initState();
}
@override
void dispose() {
timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'angle: $angle',
style: const TextStyle(
fontSize: 20,
color: Colors.greenAccent,
),
),
const SizedBox(
height: 10,
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'distance:',
style: TextStyle(fontSize: 20),
),
distance < 40
? Text(
' $distance',
style: const TextStyle(fontSize: 20, color: Colors.red),
)
: //else infinity icon
const Icon(
Icons.dangerous_sharp, //infinity icon
color: Colors.green,
size: 20,
),
],
),
Align(
alignment: Alignment.center,
child: Transform.scale(
scale: 0.8,
child: SizedBox(
width: Get.size.width,
height: Get.size.height / 1.5,
child: CustomPaint(
painter: ClockPainter(angle: angle, distance: distance),
),
),
),
),
],
);
}
}
class ClockPainter extends CustomPainter {
final double angle;
final double distance;
//create a list of points
List<Offset> points = [];
ClockPainter({this.angle = 0, this.distance = 0});
final Paint _bgPaint = Paint()
..color = Colors.white
..strokeWidth = 1
..style = PaintingStyle.stroke;
final double centerX = Get.size.width / 2;
final double centerY = Get.size.height / 2;
int circleCount = 4;
var dashBrush = Paint()
..color = CustomColors.clockOutline
..style = PaintingStyle.stroke
..strokeWidth = 1;
final Paint _points = Paint()
..color = Colors.red
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3.0)
..strokeWidth = 10;
var fillBrush = Paint()..color = CustomColors.clockBG;
var outlineBrush = Paint()
..color = CustomColors.clockOutline
..style = PaintingStyle.stroke
..strokeWidth = 20;
var centerDotBrush = Paint()..color = CustomColors.clockOutline;
var secHandBrush = Paint()
..color = CustomColors.secHandColor!
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeWidth = 15;
var radarLineBrush = Paint()
..color = CustomColors.minHandEndColor
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeWidth = 14;
int counter = 1;
@override
void paint(Canvas canvas, Size size) {
var center = Offset(centerX, centerY);
var radius = min(centerX, centerY);
final double radians = angle * pi / 180;
final double x = cos(radians);
final double y = sin(radians);
// vertical axis
canvas.drawLine(
Offset(centerX, centerY - radius), Offset(centerX, centerY), _bgPaint);
// horizontal axis
canvas.drawLine(Offset(centerX + radius, centerY - sin(pi + 0.12)),
Offset(centerX - radius, centerY), _bgPaint);
for (var i = 1; i <= circleCount; ++i) {
canvas.drawArc(
Rect.fromCenter(
center: Offset(centerX, centerY),
height: 2 * radius * i / circleCount,
width: 2 * radius * i / circleCount,
),
pi,
pi,
false,
_bgPaint);
}
var hourHandX = centerX + radius * 0.9 * x;
var hourHandY = centerY - radius * 0.9 * y;
canvas.drawLine(center, Offset(hourHandX, hourHandY), radarLineBrush);
//make a center dot inside circle at a distance
if (distance < 40) {
double pixelDistance =
distance * ((size.height - size.height * 0.166) * 0.025);
points.add(
Offset(centerX + pixelDistance * x, centerY - pixelDistance * y));
}
canvas.drawPoints(ui.PointMode.points, points, _points);
canvas.drawCircle(center, radius * 0.10, centerDotBrush);
var outer = radius;
var inner = radius * 0.9;
for (var i = 180; i < 360; i += 12) {
var x1 = centerX + outer * cos(i * pi / 180);
var y1 = centerY + outer * sin(i * pi / 180);
var x2 = centerX + inner * cos(i * pi / 180);
var y2 = centerY + inner * sin(i * pi / 180);
canvas.drawLine(Offset(x1, y1), Offset(x2, y2), dashBrush);
}
counter++;
if (counter == 100) {
points.clear();
counter = 0;
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/permission/permission.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../../components/custom_button.dart';
import '../../../controller/permission_controller.dart';
class PermissionsPage extends StatelessWidget {
static String routeName = '/permissions';
PermissionsPage({Key? key}) : super(key: key);
final PermissionController pc = Get.put(PermissionController());
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
width: double.infinity,
height: double.infinity,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment(0.6, 0.7),
end: Alignment(-0.7, 0.6),
colors: [
Color.fromRGBO(34, 52, 60, 1),
Color.fromRGBO(31, 46, 53, 1)
]),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 0.1.sw,
vertical: 0.1.sh,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'Enable Bluetooth',
),
const Text(
'We need to enable bluetooth in order to scan and connect to nearby devices',
textAlign: TextAlign.center,
),
CustomButton(
buttonText: 'Enable',
textColor: Colors.white,
buttonColor: const Color.fromRGBO(63, 223, 158, 1),
leading: true,
onTap: () {
pc.getPermission();
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/home/home.dart | import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:get/get.dart';
import '../../../controller/home_controller.dart';
import '../find_device/find_device.dart';
class Home extends StatelessWidget {
static String routeName = '/home';
Home({Key? key}) : super(key: key);
final HomeController _hc = Get.put(HomeController());
@override
Widget build(BuildContext context) {
// return StreamBuilder<BluetoothState>(
// stream: FlutterBlue.instance.state,
// initialData: BluetoothState.unknown,
// builder: (c, snapshot) {
// final state = snapshot.data;
// if (state == BluetoothState.on) {
// return FindDevicesScreen();
// }
// return BluetoothOffScreen(state: state);
// });
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Center(child: Text('Sonic')),
),
body: ListView(
children: <Widget>[
const Divider(),
const ListTile(title: Text('General')),
Obx(
() => SwitchListTile(
title: const Text('Enable Bluetooth'),
value: _hc.bluetoothState.value,
onChanged: (bool value) => _hc.bluetoothSwitch(value)),
),
ListTile(
title: const Text('Bluetooth status'),
subtitle: Obx(
() => Text(_hc.bluetoothState.value ? 'enabled' : 'disabled')),
trailing: ElevatedButton(
onPressed: () {
FlutterBluetoothSerial.instance.openSettings();
},
child: const Text('Settings'),
),
),
ListTile(
title: const Text('Local adapter address'),
subtitle: Obx(() => Text(_hc.address.value)),
),
ListTile(
title: const Text('Local adapter name'),
subtitle: Obx(() => Text(_hc.name.value)),
onLongPress: null,
),
const Divider(),
const ListTile(title: Text('Devices discovery and connection')),
ListTile(
title: ElevatedButton(
onPressed: () async {
final BluetoothDevice? selectedDevice =
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return FindDevicesScreen();
},
),
);
if (selectedDevice != null) {
debugPrint('Connect -> selected ${selectedDevice.address}');
} else {
debugPrint('Connect -> no device selected');
}
},
child: const Text('Connect to paired device to chat'),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/radar_old/radar.dart | import 'package:flutter/material.dart';
class Radar extends StatelessWidget {
const Radar({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/radar_old/radar_painter.dart | import 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sonic/controller/painter_controller.dart';
import '../../../controller/radar_controller.dart';
class RadarPainter extends CustomPainter {
final RadarController _rc = Get.find();
final PainterController _pc = Get.put(PainterController());
final Paint _bgPaint = Paint()
..color = Colors.white
..strokeWidth = 1
..style = PaintingStyle.stroke;
final Paint _paint = Paint()..style = PaintingStyle.fill;
//point for points
final Paint _points = Paint()
..color = const Color(0xff63aa65)
..strokeCap = StrokeCap.round //rounded points
..strokeWidth = 10;
int circleCount = 3;
int counter = 1;
@override
void paint(Canvas canvas, Size size) {
canvas.drawLine(Offset(size.width / 2, size.height / 2 - _pc.radius),
Offset(size.width / 2, size.height / 2 + _pc.radius), _bgPaint);
canvas.drawLine(Offset(size.width / 2 + _pc.radius, size.height / 2),
Offset(size.width / 2 - _pc.radius, size.height / 2), _bgPaint);
//draws the circles of the radar
for (var i = 1; i <= circleCount; ++i) {
canvas.drawArc(
Rect.fromCenter(
center: Offset(size.width / 2, size.height / 2),
height: 2 * _pc.radius * i / circleCount,
width: 2 * _pc.radius * i / circleCount,
),
pi,
2 * pi,
false,
_bgPaint);
// canvas.drawCircle(Offset(size.width / 2, size.height / 2),
// _pc.radius * i / circleCount, _bgPaint);
}
_paint.shader = ui.Gradient.sweep(
Offset(size.width / 2, size.height / 2),
[Colors.white.withOpacity(0.5), Colors.white.withOpacity(.5)],
[.0, 1.0],
TileMode.clamp,
.0,
pi / 12);
//draw radar line at angle provided by task object
// final int rangle = int.parse(task.radarData.last.angle);
// final int distance = int.parse(task.radarData.last.distance);
// debugPrint("rangle: $rangle"+" distance: $distance");
// canvas.save();
// double r = sqrt(pow(size.width, 2) + pow(size.height, 2));
// double startAngle = atan(size.height / size.width);
// Point p0 = Point(r * cos(startAngle), r * sin(startAngle));
// Point px = Point(r * cos(angle + startAngle), r * sin(angle + startAngle));
// canvas.translate((p0.x - px.x) / 2, (p0.y - px.y) / 2);
// canvas.rotate(angle);
//
// canvas.drawArc(
// Rect.fromCircle(
// center: Offset(size.width / 2, size.height / 2), _pc.radius: _pc.radius),
// 0,
// 0.1,
// true,
// _paint);
// canvas.restore();
//drawLine(canvas, size);
drawObject(canvas, size);
var outer = _pc.radius;
var inner = _pc.radius * 0.9;
for (var i = 0; i < 360; i += 12) {
var x1 = _pc.centerX + outer * cos(i * pi / 180);
var y1 = _pc.centerY + outer * sin(i * pi / 180);
var x2 = _pc.centerX + inner * cos(i * pi / 180);
var y2 = _pc.centerY + inner * sin(i * pi / 180);
canvas.drawLine(Offset(x1, y1), Offset(x2, y2), _pc.dashBrush);
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
//--------------------------Utiliy functions-----------------------------//
void drawObject(Canvas canvas, Size size) {
double pixelDistance =
_rc.idistance.value * ((size.height - size.height * 0.1666) * 0.025);
debugPrint("pixelDistance: $pixelDistance");
if (pixelDistance < 40) {
//draw a point on the radar
canvas.drawPoints(
ui.PointMode.points,
[
Offset(
pixelDistance *
cos(
_rc.iangle.value * 180 / pi,
),
pixelDistance *
sin(
_rc.iangle.value * 180 / pi,
),
),
],
_points);
}
// translate(width/2,height-height*0.074); // moves the starting coordinats to new location
// strokeWeight(9);
// stroke(255,10,10); // red color
// pixsDistance = iDistance*((height-height*0.1666)*0.025); // covers the distance from the sensor from cm to pixels
// // limiting the range to 40 cms
// if(iDistance<40) {
// // draws the object according to the angle and the distance
// line(pixsDistance * cos(radians(iAngle)),
// -pixsDistance * sin(radians(iAngle)),
// (width - width * 0.505) * cos(radians(iAngle)),
// -(width - width * 0.505) * sin(radians(iAngle)));
// }
}
void drawText() {
// pushMatrix();
// if(iDistance>40) {
// noObject = "Out of Range";
// }
// else {
// noObject = "In Range";
// }
// fill(0,0,0);
// noStroke();
// rect(0, height-height*0.0648, width, height);
// fill(98,245,31);
// textSize(25);
//
// text("10cm",width-width*0.3854,height-height*0.0833);
// text("20cm",width-width*0.281,height-height*0.0833);
// text("30cm",width-width*0.177,height-height*0.0833);
// text("40cm",width-width*0.0729,height-height*0.0833);
// textSize(40);
// text("Lakhan Kumawat 's Radar", width-width*0.800, height-height*0.0200);
// text("Angle: " + iAngle +" °", width-width*0.48, height-height*0.0277);
// text("Distance: ", width-width*0.26, height-height*0.0277);
// if(iDistance<40) {
// text(" " + iDistance +" cm", width-width*0.225, height-height*0.0277);
// }
// textSize(25);
// fill(98,245,60);
// translate((width-width*0.4994)+width/2*cos(radians(30)),(height-height*0.0907)-width/2*sin(radians(30)));
// rotate(-radians(-60));
// text("30°",0,0);
// resetMatrix();
// translate((width-width*0.503)+width/2*cos(radians(60)),(height-height*0.0888)-width/2*sin(radians(60)));
// rotate(-radians(-30));
// text("60°",0,0);
// resetMatrix();
// translate((width-width*0.507)+width/2*cos(radians(90)),(height-height*0.0833)-width/2*sin(radians(90)));
// rotate(radians(0));
// text("90°",0,0);
// resetMatrix();
// translate(width-width*0.513+width/2*cos(radians(120)),(height-height*0.07129)-width/2*sin(radians(120)));
// rotate(radians(-30));
// text("120°",0,0);
// resetMatrix();
// translate((width-width*0.5104)+width/2*cos(radians(150)),(height-height*0.0574)-width/2*sin(radians(150)));
// rotate(radians(-60));
// text("150°",0,0);
// popMatrix();
}
void drawLine(Canvas canvas, Size size) {
// pushMatrix();
// strokeWeight(9);
// stroke(30,250,60);
// translate(width/2,height-height*0.074); // moves the starting coordinats to new location
// line(0,0,(height-height*0.12)*cos(radians(iAngle)),-(height-height*0.12)*sin(radians(iAngle))); // draws the line according to the angle
// popMatrix();
//draw the radar line using the angle
canvas.drawLine(
Offset(size.width / 2, size.height - size.height * 0.074),
Offset(
(size.height - size.height * 0.12) *
cos(_rc.iangle.value * 180 / pi),
-(size.height - size.height * 0.12) *
sin(_rc.iangle.value * 180 / pi)),
_pc.outlineBrush);
}
void drawRadar() {
// pushMatrix();
// translate(width/2,height-height*0.074); // moves the starting coordinats to new location
// noFill();
// strokeWeight(2);
// stroke(98,245,31);
// // draws the arc lines
// arc(0,0,(width-width*0.0625),(width-width*0.0625),PI,TWO_PI);
// arc(0,0,(width-width*0.27),(width-width*0.27),PI,TWO_PI);
// arc(0,0,(width-width*0.479),(width-width*0.479),PI,TWO_PI);
// arc(0,0,(width-width*0.687),(width-width*0.687),PI,TWO_PI);
// // draws the angle lines
// line(-width/2,0,width/2,0);
// line(0,0,(-width/2)*cos(radians(30)),(-width/2)*sin(radians(30)));
// line(0,0,(-width/2)*cos(radians(60)),(-width/2)*sin(radians(60)));
// line(0,0,(-width/2)*cos(radians(90)),(-width/2)*sin(radians(90)));
// line(0,0,(-width/2)*cos(radians(120)),(-width/2)*sin(radians(120)));
// line(0,0,(-width/2)*cos(radians(150)),(-width/2)*sin(radians(150)));
// line((-width/2)*cos(radians(30)),0,width/2,0);
// popMatrix();
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/radar_old/radar_page.dart | import 'package:flutter/material.dart';
import 'package:sonic/src/screens/radar_old/radar_view.dart';
class RadarPage extends StatelessWidget {
static const String routeName = '/radarPage';
const RadarPage({super.key});
// final RadarController _controller =
// Get.put(RadarController(address: Get.arguments as String));
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF0F1532),
body: Stack(
children: [
Positioned.fill(
left: 10,
right: 10,
child: Center(
child: Stack(children: const [
Positioned.fill(
child: RadarView(),
),
Positioned(
child: Center(
child: SizedBox(
height: 70.0,
width: 60.0,
child: Text(
'0',
style: TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold),
),
),
),
),
Positioned(
child: Center(
child: SizedBox(
height: 210.0,
width: 60.0,
child: Text(
'50',
style: TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold),
),
),
),
),
Positioned(
child: Center(
child: SizedBox(
height: 390.0,
width: 80.0,
child: Text(
'100',
style: TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold),
),
),
),
),
]),
),
)
],
));
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/radar_old/radar_view.dart | import 'package:flutter/material.dart';
import 'package:sonic/src/screens/radar_old/radar_painter.dart';
class RadarView extends StatefulWidget {
const RadarView({super.key});
@override
State<StatefulWidget> createState() => _RadarViewState();
}
class _RadarViewState extends State<RadarView>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
//final radians = degrees * math.pi / 180;
//_controller.reverse(from:pi);
_controller.repeat();
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// final BackgroundCollectingTask task =
// BackgroundCollectingTask.of(context, rebuildOnChange: true);
return CustomPaint(
painter: RadarPainter(
//task: task,
),
);
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/find_device/find_device.dart | import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:get/get.dart';
import 'package:sonic/controller/find_device_controller.dart';
import '../radar/radar.dart';
import 'list_devices.dart';
class FindDevicesScreen extends StatelessWidget {
static String routeName = '/find_devices';
final FindDeviceController _dc = Get.put(FindDeviceController());
FindDevicesScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Obx(
() => Text(
_dc.isLoading.value ? 'Discovering Devices' : 'Discovered devices',
),
),
actions: <Widget>[
_dc.isLoading.value
? FittedBox(
child: Container(
margin: const EdgeInsets.all(16.0),
child: const CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
),
)
: IconButton(
icon: const Icon(Icons.replay),
onPressed: _dc.restartDiscovery,
)
],
),
body: Obx(
() => ListView.builder(
itemCount: _dc.results.length,
itemBuilder: (BuildContext context, index) {
BluetoothDiscoveryResult result = _dc.results[index];
final device = result.device;
final address = device.address;
return BluetoothDeviceListEntry(
device: device,
rssi: result.rssi,
onTap: () {
Get.toNamed(RadarView.routeName, arguments: address);
},
onLongPress: () async {
try {
bool bonded = false;
if (device.isBonded) {
debugPrint('Unbonding from ${device.address}...');
await FlutterBluetoothSerial.instance
.removeDeviceBondWithAddress(address);
debugPrint('Unbonding from ${device.address} has succed');
} else {
debugPrint('Bonding with ${device.address}...');
bonded = (await FlutterBluetoothSerial.instance
.bondDeviceAtAddress(address))!;
debugPrint(
'Bonding with ${device.address} has ${bonded ? 'succed' : 'failed'}.');
}
_dc.results[_dc.results.indexOf(result)] =
BluetoothDiscoveryResult(
device: BluetoothDevice(
name: device.name ?? '',
address: address,
type: device.type,
bondState: bonded
? BluetoothBondState.bonded
: BluetoothBondState.none,
),
rssi: result.rssi);
} catch (ex) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error occured while bonding'),
content: Text(ex.toString()),
actions: <Widget>[
TextButton(
child: const Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
},
);
},
),
),
// body: RefreshIndicator(
// onRefresh: () => _dc.,
// child: SingleChildScrollView(
// child: Column(
// children: <Widget>[
// StreamBuilder<List<BluetoothDevice>>(
// stream: Stream.periodic(const Duration(seconds: 2))
// .asyncMap((_) => FlutterBlue.instance.connectedDevices),
// initialData: const [],
// builder: (c, snapshot) => snapshot.hasData
// ? Column(
// children: snapshot.data!
// .map((d) => ListTile(
// title: Text(d.name),
// subtitle: Text(d.id.toString()),
// trailing: StreamBuilder<BluetoothDeviceState>(
// stream: d.state,
// initialData:
// BluetoothDeviceState.disconnected,
// builder: (c, snapshot) {
// if (snapshot.data ==
// BluetoothDeviceState.connected) {
// Navigator.of(context).pushNamed(
// DeviceScreen.routeName,
// arguments: d);
// }
// return Text(snapshot.data.toString());
// },
// ),
// ))
// .toList(),
// )
// : const Text('No devices connected'),
// ),
// StreamBuilder<List<ScanResult>>(
// stream: FlutterBlue.instance.scanResults,
// initialData: const [],
// builder: (c, snapshot) => snapshot.hasData
// ? Column(
// children: snapshot.data
// ?.map(
// (r) => ScanResultTile(
// result: r,
// onTap: () async {
// debugPrint('Connecting to device...${r.device.name}');
// await r.device.connect();
//
// Navigator.of(context).pushNamed(
// DeviceScreen.routeName,
// arguments: r.device);
// },
// ),
// )
// .toList() as List<Widget>,
// )
// : const Text('No devices found'),
// ),
// ],
// ),
// ),
// ),
// floatingActionButton: StreamBuilder<bool>(
// stream: FlutterBlue.instance.isScanning,
// initialData: false,
// builder: (c, snapshot) {
// if (snapshot.data!) {
// return FloatingActionButton(
// onPressed: () => FlutterBlue.instance.stopScan(),
// backgroundColor: Colors.red,
// child: const Icon(Icons.stop),
// );
// } else {
// return Obx(
// () => _deviceController.isLoading.value
// ? const Center(
// child: CircularProgressIndicator(),
// )
// : FloatingActionButton(
// child: const Icon(Icons.search),
// onPressed: () => _deviceController.refresh(),
// ),
// );
// }
// },
// ),
);
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/find_device/list_devices.dart | import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
class BluetoothDeviceListEntry extends ListTile {
BluetoothDeviceListEntry({
super.key,
required BluetoothDevice device,
int? rssi,
GestureTapCallback? onTap,
GestureLongPressCallback? onLongPress,
bool enabled = true,
}) : super(
onTap: onTap,
onLongPress: onLongPress,
enabled: enabled,
leading: const Icon(Icons.devices),
// @TODO . !BluetoothClass! class aware icon
title: Text(device.name ?? device.address),
subtitle: Text(device.address.toString()),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
rssi != null
? Container(
margin: const EdgeInsets.all(8.0),
child: DefaultTextStyle(
style: _computeTextStyle(rssi),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(rssi.toString()),
const Text('dBm'),
],
),
),
)
: const SizedBox(width: 0, height: 0),
device.isConnected
? const Icon(Icons.import_export)
: const SizedBox(width: 0, height: 0),
device.isBonded
? const Icon(Icons.link)
: const SizedBox(width: 0, height: 0),
],
),
);
static TextStyle _computeTextStyle(int rssi) {
/**/ if (rssi >= -35) {
return TextStyle(color: Colors.greenAccent[700]);
} else if (rssi >= -45) {
return TextStyle(
color: Color.lerp(
Colors.greenAccent[700], Colors.lightGreen, -(rssi + 35) / 10));
} else if (rssi >= -55) {
return TextStyle(
color: Color.lerp(
Colors.lightGreen, Colors.lime[600], -(rssi + 45) / 10));
} else if (rssi >= -65) {
return TextStyle(
color: Color.lerp(Colors.lime[600], Colors.amber, -(rssi + 55) / 10));
} else if (rssi >= -75) {
return TextStyle(
color: Color.lerp(
Colors.amber, Colors.deepOrangeAccent, -(rssi + 65) / 10));
} else if (rssi >= -85) {
return TextStyle(
color: Color.lerp(
Colors.deepOrangeAccent, Colors.redAccent, -(rssi + 75) / 10));
} else {
return const TextStyle(color: Colors.redAccent);
}
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/chats/chats.dart | import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
class ChatPage extends StatefulWidget {
static String routeName = "/chat";
final BluetoothDevice? server;
const ChatPage({super.key, this.server});
@override
State<StatefulWidget> createState() => _ChatPage();
}
class _Message {
int whom;
String text;
_Message(this.whom, this.text);
}
class _ChatPage extends State<ChatPage> {
static const clientID = 0;
BluetoothConnection? connection;
List<_Message>? messages;
String _messageBuffer = '';
final TextEditingController textEditingController = TextEditingController();
final ScrollController listScrollController = ScrollController();
bool isConnecting = true;
bool get isConnected => connection != null && connection!.isConnected;
bool isDisconnecting = false;
@override
void initState() {
super.initState();
BluetoothConnection.toAddress(widget.server!.address).then((connection) {
debugPrint('Connected to the device');
connection = connection;
setState(() {
isConnecting = false;
isDisconnecting = false;
});
connection.input!.listen(_onDataReceived).onDone(() {
// Example: Detect which side closed the connection
// There should be `isDisconnecting` flag to show are we are (locally)
// in middle of disconnecting process, should be set before calling
// `dispose`, `finish` or `close`, which all causes to disconnect.
// If we except the disconnection, `onDone` should be fired as result.
// If we didn't except this (no flag set), it means closing by remote.
if (isDisconnecting) {
debugPrint('Disconnecting locally!');
} else {
debugPrint('Disconnected remotely!');
}
if (mounted) {
setState(() {});
}
});
}).catchError((error) {
debugPrint('Cannot connect, exception occured');
debugPrint(error);
});
}
@override
void dispose() {
// Avoid memory leak (`setState` after dispose) and disconnect
if (isConnected) {
isDisconnecting = true;
connection!.dispose();
connection = null;
}
super.dispose();
}
@override
Widget build(BuildContext context) {
final List<Row> list = messages!.map((message) {
return Row(
mainAxisAlignment: message.whom == clientID
? MainAxisAlignment.end
: MainAxisAlignment.start,
children: <Widget>[
Container(
padding: const EdgeInsets.all(12.0),
margin: const EdgeInsets.only(bottom: 8.0, left: 8.0, right: 8.0),
width: 222.0,
decoration: BoxDecoration(
color:
message.whom == clientID ? Colors.blueAccent : Colors.grey,
borderRadius: BorderRadius.circular(7.0)),
child: Text(
(text) {
return text == '/shrug' ? '¯\\_(ツ)_/¯' : text;
}(message.text.trim()),
style: const TextStyle(color: Colors.white)),
),
],
);
}).toList();
return Scaffold(
appBar: AppBar(
title: (isConnecting
? Text("Connecting chat to ${widget.server!.name}...")
: isConnected
? Text("Live chat with ${widget.server!.name}")
: Text("Chat Log with ${widget.server!.name}"))),
body: SafeArea(
child: Column(
children: <Widget>[
Flexible(
child: ListView(
padding: const EdgeInsets.all(12.0),
controller: listScrollController,
children: list),
),
Row(
children: <Widget>[
Flexible(
child: Container(
margin: const EdgeInsets.only(left: 16.0),
child: TextField(
style: const TextStyle(fontSize: 15.0),
controller: textEditingController,
decoration: InputDecoration.collapsed(
hintText: isConnecting
? 'Wait until connected...'
: isConnected
? 'Type your message...'
: 'Chat got disconnected',
hintStyle: const TextStyle(color: Colors.grey),
),
enabled: isConnected,
),
),
),
Container(
margin: const EdgeInsets.all(8.0),
child: IconButton(
icon: const Icon(Icons.send),
onPressed: isConnected
? () => _sendMessage(textEditingController.text)
: null),
),
],
)
],
),
),
);
}
void _onDataReceived(Uint8List data) {
// Allocate buffer for parsed data
int backspacesCounter = 0;
for (var byte in data) {
if (byte == 8 || byte == 127) {
backspacesCounter++;
}
}
Uint8List buffer = Uint8List(data.length - backspacesCounter);
int bufferIndex = buffer.length;
// Apply backspace control character
backspacesCounter = 0;
for (int i = data.length - 1; i >= 0; i--) {
if (data[i] == 8 || data[i] == 127) {
backspacesCounter++;
} else {
if (backspacesCounter > 0) {
backspacesCounter--;
} else {
buffer[--bufferIndex] = data[i];
}
}
}
// Create message if there is new line character
String dataString = String.fromCharCodes(buffer);
int index = buffer.indexOf(13);
if (~index != 0) {
setState(() {
messages?.add(
_Message(
1,
backspacesCounter > 0
? _messageBuffer.substring(
0, _messageBuffer.length - backspacesCounter)
: _messageBuffer + dataString.substring(0, index),
),
);
_messageBuffer = dataString.substring(index);
});
} else {
_messageBuffer = (backspacesCounter > 0
? _messageBuffer.substring(
0, _messageBuffer.length - backspacesCounter)
: _messageBuffer + dataString);
}
}
void _sendMessage(String text) async {
text = text.trim();
textEditingController.clear();
if (text.isNotEmpty) {
try {
connection?.output.add(utf8.encode("$text\r\n") as Uint8List);
await connection?.output.allSent;
setState(() {
messages?.add(_Message(clientID, text));
});
Future.delayed(const Duration(milliseconds: 333)).then((_) {
listScrollController.animateTo(
listScrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 333),
curve: Curves.easeOut);
});
} catch (e) {
// Ignore error, but notify state
setState(() {});
}
}
}
}
| 0 |
mirrored_repositories/sonic/lib/src/screens | mirrored_repositories/sonic/lib/src/screens/chats/rubbish.dart | // import 'dart:convert';
// import 'package:flutter/material.dart';
// import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
//
// class RadarData{
// String distance;
// String angle;
// RadarData({required this.distance, required this.angle});
// }
//
//
// class BackgroundCollectingTask extends Model {
// static BackgroundCollectingTask of(
// BuildContext context, {
// bool rebuildOnChange = false,
// }) =>
// ScopedModel.of<BackgroundCollectingTask>(
// context,
// rebuildOnChange: rebuildOnChange,
// );
//
// final BluetoothConnection _connection;
// List<int> _buffer = List<int>.empty(growable: true);
//
// // @TODO , Such sample collection in real code should be delegated
// // (via `Stream<DataSample>` preferably) and then saved for later
// // displaying on chart (or even stright prepare for displaying).
// // @TODO ? should be shrinked at some point, endless colleting data would cause memory shortage.
// List<DataSample> samples = List<DataSample>.empty(growable: true);
//
//
// static Future<BackgroundCollectingTask> connect(
// BluetoothDevice server) async {
// final BluetoothConnection connection =
// await BluetoothConnection.toAddress(server.address);
// return BackgroundCollectingTask._fromConnection(connection);
// }
//
// void dispose() {
// _connection.dispose();
// }
//
// Future<void> start() async {
// inProgress = true;
// _buffer.clear();
// samples.clear();
// notifyListeners();
// _connection.output.add(ascii.encode('start'));
// await _connection.output.allSent;
// }
//
// Future<void> cancel() async {
// inProgress = false;
// notifyListeners();
// _connection.output.add(ascii.encode('stop'));
// await _connection.finish();
// }
//
// Future<void> pause() async {
// inProgress = false;
// notifyListeners();
// _connection.output.add(ascii.encode('stop'));
// await _connection.output.allSent;
// }
//
// Future<void> reasume() async {
// inProgress = true;
// notifyListeners();
// _connection.output.add(ascii.encode('start'));
// await _connection.output.allSent;
// }
//
// Iterable<DataSample> getLastOf(Duration duration) {
// DateTime startingTime = DateTime.now().subtract(duration);
// int i = samples.length;
// do {
// i -= 1;
// if (i <= 0) {
// break;
// }
// } while (samples[i].timestamp.isAfter(startingTime));
// return samples.getRange(i, samples.length);
// }
// }
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/constant/constant.dart | import 'package:flutter/material.dart';
class CustomColors {
static Color primaryTextColor = Colors.white;
static Color dividerColor = Colors.white54;
static Color pageBackgroundColor = const Color(0xFF2D2F41);
static Color menuBackgroundColor = const Color(0xFF242634);
static Color clockBG = const Color(0xFF444974);
static Color clockOutline = const Color(0xFFEAECFF);
static Color? secHandColor = Colors.orange[300];
static Color minHandStatColor = const Color(0xFF748EF6);
static Color minHandEndColor = Colors.green;
static Color hourHandStatColor = const Color(0xFFC279FB);
static Color hourHandEndColor = const Color(0xFFEA74AB);
}
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/controller/radar_controller.dart | import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:get/get.dart';
import '../model/data_model.dart';
class RadarController extends GetxController {
late final BluetoothConnection _connection;
List<int> _buffer = List<int>.empty(growable: true);
RxList<RadarData> radarData = List<RadarData>.empty(growable: true).obs;
RxBool inProgress = true.obs;
RxBool isConnected = false.obs;
RxBool isConnecting = true.obs;
RxBool isDisconnecting = false.obs;
RxDouble idistance = 0.0.obs;
RxDouble iangle = 0.0.obs;
final String? address;
RxBool loading = true.obs;
RadarController({required this.address});
//-----------------InitState----------------//
@override
void onInit() async {
//pass the address as parameter to onInit in the getx
debugPrint("address is $address");
if (address != null) {
initData(address);
}
super.onInit();
}
@override
void disposeId(Object id) {
if (isConnected.value) {
_connection.finish();
}
super.disposeId(id);
}
void initData(String? address) async {
//connect to address and start listening
BluetoothConnection.toAddress(address!).then((connection) {
debugPrint('Connected to the device');
_connection = connection;
isConnected.value = true;
connection.input!.listen(_processData).onDone(() {
if (isDisconnecting.value) {
debugPrint('Disconnecting locally!');
} else {
debugPrint('Disconnected remotely!');
}
});
}).catchError((error) {
debugPrint('Cannot connect, exception occured');
debugPrint(error);
});
}
void _processData(Uint8List data) {
_buffer += data;
while (true) {
// If there is a sample, and it is full sent
int index = _buffer.indexOf('.'.codeUnitAt(0));
//angle min 15 to max 165
//distance min 0 to max 2250
//max length of message = 3angle + 4distance + 1comma = 8
if (index >= 0 && _buffer.length - index >= 4) {
int separator = _buffer.indexOf(','.codeUnitAt(0));
if (separator >= 0 && _buffer.length - separator >= 2) {
//print data
String angle = String.fromCharCodes(_buffer.sublist(0, separator));
String distance =
String.fromCharCodes(_buffer.sublist(separator + 1, index));
debugPrint("------angle : $angle , distance : $distance---------");
iangle = double.parse(angle).obs;
idistance = double.parse(distance).obs;
//radarData.add(sample);
//notifyListeners();
//remove data from buffer
}
_buffer.removeRange(0, index + 1);
} else {
break;
}
}
}
}
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/controller/find_device_controller.dart | import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
class FindDeviceController extends GetxController {
Rx<bool> isLoading = false.obs;
StreamSubscription<BluetoothDiscoveryResult>? _streamSubscription;
RxList<BluetoothDiscoveryResult> results =
RxList<BluetoothDiscoveryResult>.empty(growable: true);
init() async {
if (await Permission.location.request().isGranted) {
setLoading();
_startDiscovery();
}
}
// @override
// void dispose() {
// super.dispose();
// _streamSubscription?.cancel();
// }
void setLoading() {
isLoading.value = !isLoading.value;
}
void _startDiscovery() {
_streamSubscription =
FlutterBluetoothSerial.instance.startDiscovery().listen((r) {
final existingIndex = results
.indexWhere((element) => element.device.address == r.device.address);
if (existingIndex >= 0) {
results[existingIndex] = r;
} else {
results.add(r);
}
});
_streamSubscription!.onDone(() {
isLoading.value = false;
});
}
void restartDiscovery() {
results.clear();
setLoading();
_startDiscovery();
}
//for checking the status before scanning and connecting
Future<bool> checkStatus() async {
var scanStatus = await Permission.bluetoothScan.request().isGranted;
var bluetoothConnectStatus =
await Permission.bluetoothConnect.request().isGranted;
if (scanStatus && bluetoothConnectStatus) {
return true;
} else {
return false;
}
}
@override
Future<void> refresh() async {
//start loading animation
setLoading();
bool check = await checkStatus();
if (check) {
debugPrint('Scanning...');
//update these results in a list
FlutterBlue.instance.startScan(timeout: const Duration(seconds: 4));
} else {
debugPrint("Permission not granted");
}
//stop loading animation
setLoading();
}
}
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/controller/home_controller.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:get/get.dart';
import 'package:sonic/src/screens/chats/chats.dart';
class HomeController extends GetxController {
RxBool bluetoothState = false.obs;
RxString address = "...".obs;
RxString name = "...".obs;
@override
onInit() {
super.onInit();
init();
}
init() async {
// Get current state
FlutterBluetoothSerial serial = FlutterBluetoothSerial.instance;
await serial.state.then((state) {
bluetoothState.value = state.isEnabled;
});
// Get local device address
List<BluetoothDevice> devices = await serial.getBondedDevices();
if (devices.isNotEmpty) {
address.value = devices[0].address;
name.value = devices[0].name ?? "UNKNOWN";
} else {
address.value = "NULL";
name.value = "NULL";
}
}
@override
void dispose() {
FlutterBluetoothSerial.instance.setPairingRequestHandler(null);
super.dispose();
}
void startChat(BuildContext context, BluetoothDevice server) {
Navigator.of(context).pushNamed(ChatPage.routeName, arguments: server);
}
void bluetoothSwitch(bool value) async {
if (value) {
await FlutterBluetoothSerial.instance.requestEnable();
} else {
await FlutterBluetoothSerial.instance.requestDisable();
}
init();
}
}
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/controller/painter_controller.dart | import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../constant/constant.dart';
class PainterController extends GetxController{
late double centerX;
late double centerY;
//default constructor to initialize the centerX and centerY
PainterController(){
centerX= Get.size.width / 2;
centerY = Get.size.height / 2;
}
Paint bgPaint = Paint()
..color = Colors.white
..strokeWidth = 1
..style = PaintingStyle.stroke;
Paint paint = Paint()..style = PaintingStyle.fill;
//point for points
final Paint points = Paint()
..color = const Color(0xff63aa65)
..strokeCap = StrokeCap.round //rounded points
..strokeWidth = 10;
int circleCount = 3;
int counter=1;
late double radius = min(centerX, centerY);
late Offset center = Offset(centerX, centerY);
var fillBrush = Paint()..color = CustomColors.clockBG;
var outlineBrush = Paint()
..color = CustomColors.clockOutline
..style = PaintingStyle.stroke
..strokeWidth = Get.size.width / 20;
var centerDotBrush = Paint()..color = CustomColors.clockOutline;
var dashBrush = Paint()
..color = CustomColors.clockOutline
..style = PaintingStyle.stroke
..strokeWidth = 1;
} | 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/controller/device_controller.dart | import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';
import '../components/widgets.dart';
class DeviceController extends GetxController {
Rx<BluetoothDevice> device =
Rx<BluetoothDevice>(Get.arguments as BluetoothDevice);
RxList<BluetoothService> services = RxList<BluetoothService>([]);
RxList<BluetoothCharacteristic> characteristics =
RxList<BluetoothCharacteristic>([]);
RxList<BluetoothDescriptor> descriptors = RxList<BluetoothDescriptor>([]);
//instead of big object set all the parameters manually
List<int> getRandomBytes() {
final math = Random();
return [
math.nextInt(255),
math.nextInt(255),
math.nextInt(255),
math.nextInt(255)
];
}
@override
void onInit() {
super.onInit();
device.value.discoverServices().then((value) {
services.value = value;
});
listenToBluetoothData();
}
void onReadPressed(BluetoothCharacteristic characteristic) {
characteristic.read();
}
void onWritePressed(BluetoothCharacteristic characteristic) {
characteristic.write([1, 2, 3, 4], withoutResponse: true);
}
void onNotificationPressed(BluetoothCharacteristic characteristic) {
characteristic.setNotifyValue(!characteristic.isNotifying);
}
void onReadDescriptorPressed(BluetoothDescriptor descriptor) {
descriptor.read();
}
void onWriteDescriptorPressed(BluetoothDescriptor descriptor) {
descriptor.write([1, 2, 3, 4]);
}
List<Widget> buildServiceTiles(List<BluetoothService> services) {
return services
.map(
(s) => ServiceTile(
service: s,
characteristicTiles: s.characteristics
.map(
(c) => CharacteristicTile(
characteristic: c,
onReadPressed: () => c.read(),
onWritePressed: () async {
await c.write(getRandomBytes(), withoutResponse: true);
await c.read();
},
onNotificationPressed: () async {
await c.setNotifyValue(!c.isNotifying);
await c.read();
},
descriptorTiles: c.descriptors
.map(
(d) => DescriptorTile(
descriptor: d,
onReadPressed: () => d.read(),
onWritePressed: () => d.write(getRandomBytes()),
),
)
.toList(),
),
)
.toList(),
),
)
.toList();
}
//Listen to bluetooth data and print it to the console
void listenToBluetoothData() {
device.value.state.listen((event) {
debugPrint('/----------Bluetooth Device Data----------/');
debugPrint('Device Name: ${device.value.name}');
debugPrint('Device ID: ${device.value.id}');
debugPrint('Device State: ${device.value.state}');
debugPrint('Device Services: ${device.value.services}');
debugPrint('Device MTU Size: ${device.value.mtu}');
debugPrint(
'Device isDiscoveringServices: ${device.value.isDiscoveringServices}');
debugPrint('/----------Bluetooth Device Data----------/');
});
}
}
| 0 |
mirrored_repositories/sonic/lib | mirrored_repositories/sonic/lib/controller/permission_controller.dart | import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sonic/src/screens/home/home.dart';
class PermissionController extends GetxController {
@override
onInit() {
super.onInit();
getPermission();
}
Future<void> getPermission() async {
if (await Permission.bluetoothConnect.request().isGranted) {
await [
Permission.bluetooth,
Permission.bluetoothConnect,
Permission.bluetoothScan,
Permission.bluetoothAdvertise,
].request();
Fluttertoast.showToast(msg: "Permission Granted!");
//loading.value = false;
Get.offAndToNamed(Home.routeName);
} else {
Fluttertoast.showToast(msg: "Permission Not Granted!");
}
}
}
| 0 |
mirrored_repositories/sonic | mirrored_repositories/sonic/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 in the flutter_test package. 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_test/flutter_test.dart';
import 'package:sonic/main.dart';
void main() {
testWidgets('My test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
});
}
| 0 |
mirrored_repositories/calculo_imc_estudos_flutter | mirrored_repositories/calculo_imc_estudos_flutter/lib/main.dart | import 'package:calculo_imc/view/Splash/splash.view.dart';
import 'package:flutter/material.dart';
main(List<String> args) {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home:
SplashView(),
///HomeView(),
)
);
} | 0 |
mirrored_repositories/calculo_imc_estudos_flutter/lib/view | mirrored_repositories/calculo_imc_estudos_flutter/lib/view/Splash/splash.view.dart | import 'package:calculo_imc/view/First/first.view.dart';
import 'package:calculo_imc/view/Splash/splash.view.styles.dart';
import 'package:flutter/material.dart';
import 'dart:async';
SplashViewStyles sps = new SplashViewStyles();
class SplashView extends StatefulWidget {
@override
_SplashViewState createState() => _SplashViewState();
}
class _SplashViewState extends State<SplashView> {
@override
///The thing that makes the splashView a SplashScreen
void initState() {
super.initState();
Future.delayed(
Duration(seconds: 3),
() {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => HomeView(),
),
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Container(
decoration: BoxDecoration(
gradient: sps.backgroundGradient(),
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
///Text 1
sps.textSplashView1(),
Padding(padding: EdgeInsets.only(top: 10)),
///Text 2
sps.textSplashView2(),
Padding(padding: EdgeInsets.only(top: 30)),
///Icon
sps.circleAvatarSplashView(),
],
)
],
),
);
}
}
| 0 |
mirrored_repositories/calculo_imc_estudos_flutter/lib/view | mirrored_repositories/calculo_imc_estudos_flutter/lib/view/Splash/splash.view.styles.dart | import 'package:flutter/material.dart';
class SplashViewStyles {
///Gradient
LinearGradient backgroundGradient() {
Color splashViewBackgroundTop = Colors.white;
Color splashViewBackgroundBottom = Color.fromRGBO(59, 128, 99, 1);
return LinearGradient(
colors: [splashViewBackgroundTop, splashViewBackgroundBottom],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
);
}
///Circle Avatar
CircleAvatar circleAvatarSplashView() {
Color cicleAvatarBackground = Colors.white;
Color iconBackground = Color.fromRGBO(44, 93, 72, 1);
return CircleAvatar(
backgroundColor: cicleAvatarBackground,
radius: 65.0,
child: Icon(
Icons.fitness_center,
color: iconBackground,
size: 55.0,
),
);
}
Text textSplashView1() {
Color textColor = Colors.white;
return Text(
'IMC',
style: TextStyle(
color: textColor,
fontSize: 100.0,
//shadows:
),
);
}
Text textSplashView2() {
Color textColor = Colors.white;
return Text(
'calculator',
style: TextStyle(
color: textColor,
fontSize: 41.0,
//shadows:
),
);
}
}
| 0 |
mirrored_repositories/calculo_imc_estudos_flutter/lib/view | mirrored_repositories/calculo_imc_estudos_flutter/lib/view/First/first.view.dart | import 'package:calculo_imc/view/First/first.view.styles.dart';
import 'package:flutter/material.dart';
FirstViewStyles fvs = FirstViewStyles();
class HomeView extends StatefulWidget {
@override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
TextEditingController weightController = TextEditingController();
TextEditingController heightController = TextEditingController();
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _resultsText = "";
void _resetFields() {
weightController.text = "";
heightController.text = "";
setState(() {
_resultsText = "";
});
}
void _calculate() {
setState(() {
double weight = double.parse(weightController.text);
double height = double.parse(heightController.text) / 100;
double imc = weight / (height * height);
if (imc < 18.6) {
_resultsText = "IMC = ${imc.toStringAsPrecision(4)} \n\nUnder weight ";
} else if (imc >= 18.6 && imc < 24.9) {
_resultsText = "IMC = ${imc.toStringAsPrecision(4)} \n\nIdeal weight";
} else if (imc >= 24.9 && imc < 29.9) {
_resultsText =
"IMC = ${imc.toStringAsPrecision(4)} \n\nSlightly overweight";
} else if (imc >= 29.9 && imc < 34.9) {
_resultsText =
"IMC = ${imc.toStringAsPrecision(4)} \n\nFirst level obesity";
} else if (imc >= 34.9 && imc < 39.9) {
_resultsText =
"IMC = ${imc.toStringAsPrecision(4)} \n\nSecond level obesity";
} else if (imc >= 40) {
_resultsText =
"IMC = ${imc.toStringAsPrecision(4)} \n\nThird level obesity";
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: fvs.appBar(_resetFields),
backgroundColor: fvs.backGroundColor(),
body: Stack(
children: [
///Container Verde
fvs.container1Stack(),
SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(padding: EdgeInsets.only(bottom: 90)),
///Icon Avatar
fvs.iconAvatarStack(),
Padding(padding: EdgeInsets.only(bottom: 72)),
///Entrada de texto para peso
fvs.textFormField("Weight (Kg)", weightController),
SizedBox(height: 40),
///Entrada de texto para altura
fvs.textFormField("Height (Cm)", heightController),
SizedBox(height: 72),
///Botão de Calcular
fvs.calculateButton(_calculate, _formKey),
SizedBox(height: 40),
///Texto "Results"
fvs.resultText(_resultsText),
SizedBox(height: 40),
///Saída de texto da classificação do IMC
///Saída do resultado do cálculo
],
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/calculo_imc_estudos_flutter/lib/view | mirrored_repositories/calculo_imc_estudos_flutter/lib/view/First/first.view.styles.dart | import 'package:flutter/material.dart';
//import 'package:icon_shadow/icon_shadow.dart';
class FirstViewStyles {
///BackGround Color
Color backGroundColor() => Colors.white;
///AppBar
AppBar appBar(onPressed) {
String textAppBar = "IMC Calculator";
Color backgroundColor = Color.fromRGBO(59, 128, 99, 1);
return AppBar(
title: Text(
textAppBar,
),
centerTitle: true,
backgroundColor: backgroundColor,
actions: [
IconButton(icon: Icon(Icons.refresh), onPressed: onPressed),
],
);
}
///Container1 Stack
Container container1Stack() {
Color color = Color.fromRGBO(132, 176, 157, 1);
return Container(
color: color,
);
}
///Container2 Stack
Container container2Stack() {
Color color = Colors.white;
double height = 138;
return Container(
height: height,
color: color,
);
}
///Icon Avatar Stack
Align iconAvatarStack() {
Color backgroundColor = Color.fromRGBO(59, 128, 99, 1);
Color colorIcon = Colors.white;
double iconSize = 60.0;
Color colorShadow = Color.fromRGBO(0, 0, 0, 0.31);
double blourRadius = 20;
return Align(
alignment: Alignment(0, -0.74),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
boxShadow: [
BoxShadow(
color: colorShadow,
blurRadius: blourRadius,
)
],
),
child: CircleAvatar(
backgroundColor: backgroundColor,
radius: iconSize,
child: Icon(
Icons.fitness_center,
color: colorIcon,
size: iconSize,
),
),
),
);
}
///Entrada de dados para Peso/Altura
Container textFormField(String hintText, controller) {
double height = 45;
double width = 370;
Color containerColor = Colors.white;
Color hintTextColor = Colors.grey;
return Container(
height: height,
width: width,
decoration: BoxDecoration(
color: containerColor,
borderRadius: BorderRadius.circular(27),
),
child: TextFormField(
keyboardType:
TextInputType.numberWithOptions(signed: true, decimal: true),
decoration: InputDecoration(
contentPadding: EdgeInsets.only(left: 20),
border: InputBorder.none,
hintText: hintText,
hintStyle: TextStyle(
color: hintTextColor,
),
),
controller: controller,
// ignore: missing_return
validator: (value) {
if (value.isEmpty) {
return "Insert the data!";
}
},
),
);
}
///Botão de Calcular
Container calculateButton(onPressed, formKey) {
double height = 45;
double width = 370;
Color buttonColor = Color.fromRGBO(44, 93, 72, 1);
String buttonText = "Calculate";
double fontSize = 18;
Color buttonTextColor = Colors.white;
return Container(
height: height,
width: width,
child: RaisedButton(
onPressed: () {
if (formKey.currentState.validate()) {
onPressed();
}
},
//onPressed,
color: buttonColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(27),
),
child: Text(
buttonText,
style: TextStyle(
color: buttonTextColor,
fontSize: fontSize,
),
),
),
);
}
///Texto de Resultado
Text resultText(String text) {
Color textColor1 = Color.fromRGBO(44, 93, 72, 1);
Color textColor2 = Colors.grey[200];
Color textColor;
double fontSize = 23;
if (text == "Results") {
textColor = textColor1;
} else {
textColor = textColor2;
}
return Text(
text,
style: TextStyle(
color: textColor,
fontSize: fontSize,
fontWeight: FontWeight.bold,
),
);
}
}
| 0 |
mirrored_repositories/gps-logger-flutter | mirrored_repositories/gps-logger-flutter/lib/globalVar.dart | library lat_long.globals;
int counter = 0; | 0 |
mirrored_repositories/gps-logger-flutter | mirrored_repositories/gps-logger-flutter/lib/main.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'pages/current_location_widget.dart';
import 'pages/location_stream_widget.dart';
import 'pages/show_maps_widget.dart';
void main() => runApp(GeoLogger(
storage: PositionStorage(),
));
enum TabItem {
singleLocation,
locationStream,
ViewMap,
}
class GeoLogger extends StatefulWidget {
final PositionStorage storage;
const GeoLogger({Key key, this.storage}) : super(key: key);
@override
State<GeoLogger> createState() => BottomNavigationState();
}
class BottomNavigationState extends State<GeoLogger> {
TabItem _currentItem = TabItem.singleLocation;
final List<TabItem> _bottomTabs = [
TabItem.singleLocation,
TabItem.locationStream,
TabItem.ViewMap,
];
@override
void initState() {
super.initState();
widget.storage.writePosition(
"Timestamp", "Latitude", "Longitude", "Speed", FileMode.write);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('Geologger'),
),
body: _buildBody(),
bottomNavigationBar: _buildBottomNavigationBar(),
),
);
}
Widget _buildBody() {
switch (_currentItem) {
case TabItem.locationStream:
return LocationStreamWidget(
storage: PositionStorage(),
);
case TabItem.singleLocation:
return CurrentLocationWidget(androidFusedLocation: true);
case TabItem.ViewMap:
return ShowMapsWidget(
storage: PositionStorage(),
);
default:
throw 'Unknown $_currentItem';
}
}
Widget _buildBottomNavigationBar() {
return BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: _bottomTabs
.map((tabItem) =>
_buildBottomNavigationBarItem(_icon(tabItem), tabItem))
.toList(),
onTap: _onSelectTab,
);
}
BottomNavigationBarItem _buildBottomNavigationBarItem(
IconData icon, TabItem tabItem) {
final String text = _title(tabItem);
final Color color =
_currentItem == tabItem ? Theme.of(context).primaryColor : Colors.grey;
return BottomNavigationBarItem(
icon: Icon(
icon,
color: color,
),
title: Text(
text,
style: TextStyle(
color: color,
),
),
);
}
void _onSelectTab(int index) {
TabItem selectedTabItem = _bottomTabs[index];
setState(() {
_currentItem = selectedTabItem;
});
}
String _title(TabItem item) {
switch (item) {
case TabItem.singleLocation:
return 'Single (Fused)';
case TabItem.locationStream:
return 'Record Location';
case TabItem.ViewMap:
return 'View Map';
default:
throw 'Unknown: $item';
}
}
IconData _icon(TabItem item) {
switch (item) {
case TabItem.singleLocation:
return Icons.location_on;
case TabItem.locationStream:
return Icons.clear_all;
case TabItem.ViewMap:
return Icons.map;
default:
throw 'Unknown: $item';
}
}
}
| 0 |
mirrored_repositories/gps-logger-flutter/lib | mirrored_repositories/gps-logger-flutter/lib/common_widgets/placeholder_widget.dart | import 'package:flutter/material.dart';
class PlaceholderWidget extends StatelessWidget {
const PlaceholderWidget(this.title, this.message);
final String title;
final String message;
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(title,
style: const TextStyle(fontSize: 32.0, color: Colors.black54),
textAlign: TextAlign.center),
Text(message,
style: const TextStyle(fontSize: 16.0, color: Colors.black54),
textAlign: TextAlign.center),
],
),
);
}
}
| 0 |
mirrored_repositories/gps-logger-flutter/lib | mirrored_repositories/gps-logger-flutter/lib/pages/location_stream_widget.dart | import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:path_provider/path_provider.dart';
import '../common_widgets/placeholder_widget.dart';
class LocationStreamWidget extends StatefulWidget {
final PositionStorage storage;
const LocationStreamWidget({Key key, this.storage}) : super(key: key);
@override
State<LocationStreamWidget> createState() => LocationStreamState();
}
class PositionStorage {
Future<String> get externalLocalPath async {
final directory = await getExternalStorageDirectory();
return directory.path;
}
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await externalLocalPath;
return File('$path/loggerfile.csv');
}
Future<File> writePosition(String timestamp, String latitude,
String longitude, String speed, FileMode fileMode) async {
final file = await _localFile;
return file.writeAsString('$timestamp,$latitude,$longitude,$speed\n',
mode: fileMode);
}
Future<File> writeCounter(int counter) async {
final location = await _localPath;
final file = File('$location/counter.txt');
// Write the file
return file.writeAsString('$counter');
}
Future<int> readCounter() async {
try {
final location = await _localPath;
final file = File('$location/counter.txt');
// Read the file
String contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0
return 0;
}
}
}
class LocationStreamState extends State<LocationStreamWidget> {
StreamSubscription<Position> _positionStreamSubscription;
final List<Position> _positions = <Position>[];
void _toggleListening() {
if (_positionStreamSubscription == null) {
const LocationOptions locationOptions =
LocationOptions(accuracy: LocationAccuracy.best, distanceFilter: 10);
final Stream<Position> positionStream =
Geolocator().getPositionStream(locationOptions);
_positionStreamSubscription =
positionStream.listen((Position position) => setState(() {
_positions.add(position);
widget.storage.writePosition(
position.timestamp.toString(),
position.latitude.toString(),
position.longitude.toString(),
position.speed.toString(),
FileMode.append);
}));
_positionStreamSubscription.pause();
}
setState(() {
if (_positionStreamSubscription.isPaused) {
_positionStreamSubscription.resume();
} else {
_positionStreamSubscription.pause();
}
});
}
@override
void dispose() {
if (_positionStreamSubscription != null) {
_positionStreamSubscription.cancel();
_positionStreamSubscription = null;
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<GeolocationStatus>(
future: Geolocator().checkGeolocationPermissionStatus(),
builder:
(BuildContext context, AsyncSnapshot<GeolocationStatus> snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.data == GeolocationStatus.denied) {
return PlaceholderWidget('Location services disabled',
'Enable location services for this App using the device settings.');
}
return _buildListView();
});
}
Widget _buildListView() {
final List<Widget> listItems = <Widget>[
ListTile(
title: RaisedButton(
child: _buildButtonText(),
color: _determineButtonColor(),
padding: const EdgeInsets.all(8.0),
onPressed: _toggleListening,
),
),
];
listItems.addAll(_positions
.map((Position position) => PositionListItem(position))
.toList());
return ListView(
children: listItems,
);
}
bool _isListening() => !(_positionStreamSubscription == null ||
_positionStreamSubscription.isPaused);
Widget _buildButtonText() {
return Text(_isListening() ? 'Stop listening' : 'Start listening');
}
Color _determineButtonColor() {
return _isListening() ? Colors.red : Colors.green;
}
}
class PositionListItem extends StatefulWidget {
const PositionListItem(this._position);
final Position _position;
@override
State<PositionListItem> createState() => PositionListItemState(_position);
}
class PositionListItemState extends State<PositionListItem> {
PositionListItemState(this._position);
final Position _position;
String _address = '';
@override
Widget build(BuildContext context) {
final Row row = Row(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
'Lat: ${_position.latitude}',
style: const TextStyle(fontSize: 16.0, color: Colors.black),
),
Text(
'Lon: ${_position.longitude}',
style: const TextStyle(fontSize: 16.0, color: Colors.black),
),
]),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
_position.timestamp.toLocal().toString(),
style: const TextStyle(fontSize: 14.0, color: Colors.grey),
)
]),
),
],
);
return ListTile(
onTap: _onTap,
title: row,
subtitle: Text(_address),
);
}
Future<void> _onTap() async {
String address = 'unknown';
final List<Placemark> placemarks = await Geolocator()
.placemarkFromCoordinates(_position.latitude, _position.longitude);
if (placemarks != null && placemarks.isNotEmpty) {
address = _buildAddressString(placemarks.first);
}
setState(() {
_address = '$address';
});
}
static String _buildAddressString(Placemark placemark) {
final String name = placemark.name ?? '';
final String city = placemark.locality ?? '';
final String state = placemark.administrativeArea ?? '';
final String country = placemark.country ?? '';
return '$name, $city, $state, $country';
}
}
| 0 |
mirrored_repositories/gps-logger-flutter/lib | mirrored_repositories/gps-logger-flutter/lib/pages/current_location_widget.dart | import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import '../common_widgets/placeholder_widget.dart';
class CurrentLocationWidget extends StatefulWidget {
const CurrentLocationWidget({
Key key,
/// If set, enable the FusedLocationProvider on Android
@required this.androidFusedLocation,
}) : super(key: key);
final bool androidFusedLocation;
@override
_LocationState createState() => _LocationState();
}
class _LocationState extends State<CurrentLocationWidget> {
Position _currentPosition;
@override
void initState() {
super.initState();
_initCurrentLocation();
}
@override
void didUpdateWidget(Widget oldWidget) {
super.didUpdateWidget(oldWidget);
setState(() {
_currentPosition = null;
});
_initCurrentLocation();
}
// Platform messages are asynchronous, so we initialize in an async method.
_initCurrentLocation() {
Geolocator()
..forceAndroidLocationManager = !widget.androidFusedLocation
..getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
).then((position) {
if (mounted) {
setState(() => _currentPosition = position);
}
}).catchError((e) {
//
});
}
@override
Widget build(BuildContext context) {
return FutureBuilder<GeolocationStatus>(
future: Geolocator().checkGeolocationPermissionStatus(),
builder:
(BuildContext context, AsyncSnapshot<GeolocationStatus> snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.data == GeolocationStatus.denied) {
return const PlaceholderWidget('Access to location denied',
'Allow access to the location services for this App');
}
return Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 32,
vertical: 16,
),
child: Text(
_fusedLocationNote(),
style: TextStyle(
fontSize: 30.0,
),
textAlign: TextAlign.center,
),
),
// PlaceholderWidget(
// 'Last known location:', _lastKnownPosition.toString()),
_currentPosition == null
? CircularProgressIndicator()
: PlaceholderWidget(
'Current location:', _currentPosition.toString()),
Container(
height: 10,
),
_currentPosition == null
? CircularProgressIndicator()
: PlaceholderWidget(
'Speed:',
_currentPosition.speed.toString(),
)
],
),
);
});
}
String _fusedLocationNote() {
return 'Coordinates';
}
}
| 0 |
mirrored_repositories/gps-logger-flutter/lib | mirrored_repositories/gps-logger-flutter/lib/pages/show_maps_widget.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'location_stream_widget.dart';
class ShowMapsWidget extends StatefulWidget {
final PositionStorage storage;
const ShowMapsWidget({Key key, this.storage}) : super(key: key);
@override
_ShowMapsState createState() => _ShowMapsState();
}
class _ShowMapsState extends State<ShowMapsWidget> {
GoogleMapController mapController;
LatLng _center = const LatLng(30.768088, 76.786227);
final Set<Marker> _markers = Set();
// ignore: avoid_init_to_null
List<FileSystemEntity> files = null;
String _path = 'One';
bool _filePicked = false;
String _fileName = "Choose File";
List<String> fileNames;
_dropDownCallback() async {
setState(() {
_filePicked = true;
_markers.clear();
_fileName = _getFileName(_path);
});
try {
markPlaces(); // Placing Markers on the Screen
} catch (Exception) {
print("Exception Occurred: " + Exception.toString());
}
}
_removeFile() async {
setState(() {
_filePicked = false;
_fileName = "Choose File";
_path = "-";
_markers.clear();
});
_shiftToCurrentPosition();
}
@override
initState() {
super.initState();
_listOfFiles();
}
void _listOfFiles() async {
final directory = await widget.storage.externalLocalPath;
setState(() {
files = Directory("$directory/").listSync();
fileNames = files.map((file) => file.path).toList();
});
}
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
_shiftToCurrentPosition();
}
@override
Widget build(BuildContext context) {
return Stack(children: <Widget>[
GoogleMap(
onMapCreated: _onMapCreated,
markers: _markers,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
),
Positioned(
top: 20,
right: 15,
left: 15,
height: 60,
child: Container(
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
splashColor: Colors.green,
icon: Icon(_filePicked ? Icons.check : Icons.insert_drive_file),
color: Colors.green,
onPressed: () {},
),
Text(_fileName),
_filePicked == false
? Padding(
padding: EdgeInsets.only(left: 5),
child: files == null
? CircularProgressIndicator()
: _dropDownWidget(),
)
: Container(),
_filePicked
? IconButton(
icon: Icon(Icons.clear),
color: Colors.blueGrey,
tooltip: "Remove selected file",
onPressed: () => _removeFile(),
)
: Container(),
],
),
),
),
_filePicked == false
? Padding(
padding: const EdgeInsets.all(27.0),
child: Align(
alignment: Alignment.bottomRight,
child: FloatingActionButton(
onPressed: () => _shiftToCurrentPosition(),
materialTapTargetSize: MaterialTapTargetSize.padded,
backgroundColor: Colors.blueAccent,
child: const Icon(Icons.my_location, size: 25.0),
),
),
)
: Container(),
]);
}
void _shiftToCurrentPosition() async {
Position position = await currentLocation();
double currentLatitude = position.latitude;
double currentLongitude = position.longitude;
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
bearing: 270.0,
target: LatLng(currentLatitude, currentLongitude),
zoom: 17.0,
),
),
);
setState(() {
_markers.clear();
_markers.add(
Marker(
markerId: MarkerId('Current-Location'),
position: LatLng(currentLatitude, currentLongitude),
infoWindow: InfoWindow(
title: 'Current Location',
snippet: 'This shows your current location',
)),
);
});
}
Future<Position> currentLocation() async {
Geolocator geoLocator = Geolocator()..forceAndroidLocationManager = true;
Position position = await geoLocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
print("GOT ITTTTTTTTTTTT");
return position;
}
Widget _dropDownWidget() {
return DropdownButton<String>(
iconSize: 24,
elevation: 16,
hint: Text("CSV Files"),
style: TextStyle(color: Colors.green),
onChanged: (String newValue) {
setState(() {
_path = newValue;
_dropDownCallback();
});
},
items: fileNames.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(_getFileName(value)),
);
}).toList(),
);
}
String _getFileName(String result) {
final listSplit = result.split('/');
return listSplit[listSplit.length - 1];
}
markPlaces() async {
final file = File(_path);
// Read the file
String contents = await file.readAsString();
List<String> listOfStrings = contents.split('\n');
for (String string in listOfStrings) {
List<String> latLong = string.split(',');
print(latLong);
if (latLong.length <= 1 || latLong[1] == 'Latitude')
continue;
else {
setState(() {
_markers.add(Marker(
markerId: MarkerId("$string"),
position:
LatLng(double.parse(latLong[1]), double.parse(latLong[2])),
));
});
if (_markers.length >= 2)
setState(() {
mapController.animateCamera(CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: _markers.elementAt(_markers.length - 1).position,
northeast: _markers.elementAt(0).position),
100.0));
});
}
}
}
}
| 0 |
mirrored_repositories/Flutter-Course | mirrored_repositories/Flutter-Course/lib/main.dart | import 'package:flutter/material.dart';
import 'src/04/movies_api.dart' as app;
void main() {
//runApp(MyApp());
app.main();
}
// ignore: use_key_in_widget_constructors
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/Flutter-Course/lib/src | mirrored_repositories/Flutter-Course/lib/src/01/converer.dart | import 'package:flutter/material.dart';
void main() {
runApp(const Converter());
}
class Converter extends StatefulWidget {
const Converter({Key? key}) : super(key: key);
@override
_ConverterState createState() => _ConverterState();
}
class _ConverterState extends State<Converter> {
String? _amountUSD;
String? _amountLEI = '';
final TextEditingController _controller = TextEditingController();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
bool isNumeric(String s) {
if (s == null) {
return false;
}
return double.tryParse(s) != null;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Currency Convertor'),
),
body: Container(
color: Colors.red,
child: Directionality(
textDirection: TextDirection.ltr,
child: Container(
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Image.network(
'https://1.bp.blogspot.com/-kDEsmpQSxIY/VC6lD5YuHyI/AAAAAAAAJ6k/BgZzmegj_sw/s1600/Dollars-009.jpg'),
Padding(
padding: const EdgeInsets.all(32.0),
child: Form(
key: _formKey,
child: TextFormField(
validator: (String? _amountUSD) {
if (_amountUSD == null || !isNumeric(_amountUSD)) {
return 'Please enter some valid number';
} else {
return null;
}
},
controller: _controller,
decoration: InputDecoration(
hintText: 'Enter the amount in USD',
suffix: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_controller.clear();
setState(() {
_amountUSD = null;
});
},
),
),
onChanged: (String value) {
setState(() {
if (value.isEmpty) {
_amountUSD = null;
} else {
_amountUSD = value;
}
});
},
),
),
),
Padding(
padding: const EdgeInsets.all(32.0),
child: TextButton(
onPressed: () {
setState(() {
if (_formKey.currentState!.validate()) {
_amountLEI = (double.parse(_amountUSD.toString()) * 4.06).toStringAsFixed(2) + ' LEI';
} else {
_amountLEI = '';
}
});
},
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'CONVERT!',
style: TextStyle(
fontSize: 16.0,
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.blueAccent),
),
),
),
Text(
_amountLEI.toString(),
style: const TextStyle(color: Colors.black54, fontSize: 29.0, fontWeight: FontWeight.bold),
),
],
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Course/lib/src | mirrored_repositories/Flutter-Course/lib/src/02/guess_a_number.dart | import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_course/src/02/number_shape.dart';
void main() {
runApp(const MaterialApp(
home: GuessANumber(),
));
}
class GuessANumber extends StatefulWidget {
const GuessANumber({Key? key}) : super(key: key);
@override
_GuessANumberState createState() => _GuessANumberState();
}
class _GuessANumberState extends State<GuessANumber> {
String? _number;
static Random random = Random();
int randomNumber = random.nextInt(100) + 1;
String? verdict = '';
String? buttonText = 'Guess';
String? tried = '';
final TextEditingController fieldText = TextEditingController();
void resetField() {
buttonText = 'Guess';
randomNumber = random.nextInt(100) + 1;
verdict = '';
_number = '';
tried = '';
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute<NumberShape>(builder: (BuildContext context) => const NumberShape()));
},
child: const Icon(Icons.arrow_right),
backgroundColor: Colors.green,
),
appBar: AppBar(
title: const Text('Guess my number'),
centerTitle: true,
),
body: Container(
color: Colors.red,
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Container(
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Text(
"I'm thinking of a number between \n 1 and 100.",
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
),
const Padding(
padding: EdgeInsets.all(32.0),
child: Text(
"It's your turn to guess my number!",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
if (verdict != '')
Text(
tried.toString(),
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 36),
),
if (verdict != '')
Text(
verdict.toString(),
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 36),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Material(
elevation: 6.0,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Padding(
padding: EdgeInsets.all(16.0),
child: Text(
'Try a number!',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0),
child: TextField(
controller: fieldText,
keyboardType: TextInputType.number,
onChanged: (String value) {
_number = value;
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextButton(
onPressed: () {
setState(() {
print(randomNumber);
fieldText.clear();
if (buttonText == 'Reset') {
resetField();
} else if (int.tryParse(_number.toString()) != null) {
tried = 'You tried $_number ';
final int _numberInt = int.parse(_number.toString());
if (_numberInt == randomNumber) {
verdict = 'You guessed right!';
showDialog<TextButton>(
context: context,
barrierDismissible: false,
builder: (_) => AlertDialog(
title: const Text('You guessed right'),
content: Text('It was $_number'),
actions: <Widget>[
TextButton(
onPressed: () {
setState(() {
resetField();
Navigator.of(context).pop();
});
},
child: const Text('Try again!')),
TextButton(
onPressed: () {
setState(() {
buttonText = 'Reset';
Navigator.of(context).pop();
});
},
child: const Text('ok'))
],
),
);
} else if (_numberInt < randomNumber) {
verdict = 'Try Higher';
} else {
verdict = 'Try Lower';
}
}
});
},
child: Text(
buttonText.toString(),
style: const TextStyle(color: Colors.black),
),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.grey),
),
),
)
],
),
),
),
],
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Course/lib/src | mirrored_repositories/Flutter-Course/lib/src/02/number_shape.dart | import 'dart:math';
import 'package:flutter/material.dart';
class NumberShape extends StatefulWidget {
const NumberShape({Key? key}) : super(key: key);
@override
_NumberShapeState createState() => _NumberShapeState();
}
class _NumberShapeState extends State<NumberShape> {
final TextEditingController fieldText = TextEditingController();
String? _number;
String? _outMessage = '';
void verifyNumber() {
bool isSquare = false;
bool isTriangular = false;
if (isInteger(sqrt(int.parse(_number.toString())))) {
isSquare = true;
}
if (perfectCube(int.parse(_number.toString()))) {
isTriangular = true;
}
if (isSquare && isTriangular) {
_outMessage = 'Number $_number is SQUARE and \nTRIANGULAR';
} else if (isSquare) {
_outMessage = 'Number $_number is SQUARE ';
} else if (isTriangular) {
_outMessage = 'Number $_number is TRIANGULAR ';
} else {
_outMessage = 'Number $_number is neither SQUARE or \nTRIANGULAR';
}
}
bool perfectCube(int N) {
int cube;
for (int i = 1; i <= N; i++) {
cube = i * i * i;
if (cube == N) {
return true;
} else if (cube > N) {
return false;
}
}
return false;
}
bool isInteger(num value) => value is int || value == value.roundToDouble();
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.verified_user_outlined),
backgroundColor: Colors.green,
onPressed: () {
if (int.tryParse(_number.toString()) != null) {
verifyNumber();
}
showDialog<Text>(
context: context,
builder: (_) => AlertDialog(
title: Text(_number.toString()),
content: Text(_outMessage.toString()),
),
);
fieldText.clear();
},
),
appBar: AppBar(
title: const Text('Number Shapes'),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
const Center(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 24),
child: Text(
'Please input a number to see if it is square or triangular',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: TextField(
controller: fieldText,
keyboardType: TextInputType.number,
onChanged: (String value) {
_number = value;
},
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Course/lib/src | mirrored_repositories/Flutter-Course/lib/src/04/view_movie.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_course/src/04/models/movie.dart';
class ViewMovieS extends StatefulWidget {
const ViewMovieS({Key? key, required this.movie}) : super(key: key);
final Movie movie;
@override
_ViewMovieSState createState() => _ViewMovieSState();
}
class _ViewMovieSState extends State<ViewMovieS> {
bool _isLoading = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.movie.title),
centerTitle: true,
),
body: _isLoading
? GestureDetector(
onTap: () {
setState(
() {
if (_isLoading) {
_isLoading = false;
}
},
);
},
child: AnimatedContainer(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(widget.movie.largeCoverImage),
),
),
duration: const Duration(seconds: 2),
),
)
: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(widget.movie.largeCoverImage),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.1), BlendMode.dstATop),
),
color: Colors.white),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: ListView.separated(
separatorBuilder: (BuildContext context, int index) {
return const SizedBox(
height: 10,
);
},
itemCount: 5,
itemBuilder: (BuildContext context, int index) {
final String genre = widget.movie.genres.join('/');
if (index == 0) {
return Text(
widget.movie.title,
style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
);
} else if (index == 1) {
return Text(
widget.movie.year.toString(),
style: const TextStyle(fontWeight: FontWeight.bold),
);
} else if (index == 2) {
return Text(
genre.toString(),
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
);
} else if (index == 3)
return Wrap(
direction: Axis.horizontal,
spacing: 100,
crossAxisAlignment: WrapCrossAlignment.center,
alignment: WrapAlignment.start,
children: <Widget>[
Wrap(
children: <Widget>[
GestureDetector(
onTap: () {
setState(
() {
if (!_isLoading) {
_isLoading = true;
}
},
);
},
child: Image.network(
widget.movie.mediumCoverImage,
width: 230,
height: 345,
),
),
],
),
Wrap(
direction: Axis.vertical,
spacing: 32,
crossAxisAlignment: WrapCrossAlignment.center,
alignment: WrapAlignment.start,
// ignore: prefer_const_literals_to_create_immutables
children: <Widget>[
Wrap(
direction: Axis.horizontal,
spacing: 10,
alignment: WrapAlignment.start,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
const Icon(Icons.favorite, color: Colors.lightGreen, semanticLabel: 'Likes'),
Text(
widget.movie.rating.toString(),
style: const TextStyle(fontWeight: FontWeight.bold),
),
],
),
Wrap(
direction: Axis.horizontal,
spacing: 10,
alignment: WrapAlignment.start,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
const Icon(Icons.timer, color: Colors.lightGreen, semanticLabel: 'RunTime'),
Text(
widget.movie.runtime.toString(),
style: const TextStyle(fontWeight: FontWeight.bold),
),
],
),
Wrap(
direction: Axis.horizontal,
spacing: 10,
alignment: WrapAlignment.start,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
const Icon(Icons.language, color: Colors.lightGreen, semanticLabel: 'language'),
Text(
widget.movie.language.toUpperCase(),
style: const TextStyle(fontWeight: FontWeight.bold),
),
],
),
],
),
],
);
else if (index == 4) {
return Column(
children: <Widget>[
const Text(
'Description',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Center(
child: Text(widget.movie.summary),
),
const SizedBox(height: 16),
Text(
'Uploaded at: ' + widget.movie.dateUploaded,
style: const TextStyle(fontWeight: FontWeight.bold),
),
],
);
}
return Text(widget.movie.mediumCoverImage);
},
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Course/lib/src | mirrored_repositories/Flutter-Course/lib/src/04/movies_api.dart | import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_course/src/04/models/movie.dart';
import 'package:flutter_course/src/04/view_movie.dart';
import 'package:http/http.dart';
// ignore_for_file: file_names
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final List<Movie> _movies = <Movie>[];
bool _isLoading = true;
@override
void initState() {
super.initState();
_getMovies();
}
Future<void> _getMovies() async {
final Uri url = Uri(
scheme: 'https',
host: 'yts.mx',
pathSegments: <String>['api', 'v2', 'list_movies.json'],
);
final Response response = await get(url);
final Map<String, dynamic> body = jsonDecode(response.body) as Map<String, dynamic>;
final Map<String, dynamic> data = body['data'] as Map<String, dynamic>;
final List<dynamic> movies = data['movies'] as List<dynamic>;
setState(
() {
for (int i = 0; i < movies.length; i++) {
final Map<String, dynamic> movie = movies[i] as Map<String, dynamic>;
_movies.add(Movie.fromJson(movie));
}
_isLoading = false;
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: _isLoading
? const Center(
child: CircularProgressIndicator(),
)
: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: .69,
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
),
itemCount: _movies.length,
itemBuilder: (BuildContext context, int index) {
final Movie movie = _movies[index];
return InkResponse(
onTap: () {
Navigator.push(
context,
MaterialPageRoute<ViewMovieS>(
builder: (BuildContext context) => ViewMovieS(
movie: movie,
),
),
);
},
child: GridTile(
child: Image.network(
movie.mediumCoverImage,
fit: BoxFit.cover,
),
footer: GridTileBar(
backgroundColor: Colors.black38,
title: Text(movie.title),
subtitle: Text(movie.summary),
),
),
);
},
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Course/lib/src/04 | mirrored_repositories/Flutter-Course/lib/src/04/models/serializers.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'serializers.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializers _$serializers = (new Serializers().toBuilder()
..add(Movie.serializer)
..addBuilderFactory(const FullType(BuiltList, const [const FullType(String)]), () => new ListBuilder<String>()))
.build();
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/Flutter-Course/lib/src/04 | mirrored_repositories/Flutter-Course/lib/src/04/models/movie.dart | import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:flutter_course/src/04/models/serializers.dart';
part 'movie.g.dart';
abstract class Movie implements Built<Movie, MovieBuilder> {
factory Movie([void Function(MovieBuilder) updates]) = _$Movie;
factory Movie.fromJson(Map<String, dynamic> json) {
return serializers.deserializeWith(serializer, json) as Movie;
}
Movie._();
int get id;
String get url;
@BuiltValueField(wireName: 'imdb_code')
String get imdbCode;
String get title;
@BuiltValueField(wireName: 'title_english')
String get titleEnglish;
@BuiltValueField(wireName: 'title_long')
String get titleLong;
String get slug;
int get year;
num get rating;
int get runtime;
BuiltList<String> get genres;
String get summary;
@BuiltValueField(wireName: 'description_full')
String get descriptionFull;
String get synopsis;
@BuiltValueField(wireName: 'yt_trailer_code')
String get ytTrailerCode;
String get language;
@BuiltValueField(wireName: 'mpa_rating')
String get mpaRating;
@BuiltValueField(wireName: 'background_image')
String get backgroundImage;
@BuiltValueField(wireName: 'background_image_original')
String get backgroundImageOriginal;
@BuiltValueField(wireName: 'small_cover_image')
String get smallCoverImage;
@BuiltValueField(wireName: 'medium_cover_image')
String get mediumCoverImage;
@BuiltValueField(wireName: 'large_cover_image')
String get largeCoverImage;
String get state;
@BuiltValueField(wireName: 'date_uploaded')
String get dateUploaded;
@BuiltValueField(wireName: 'date_uploaded_unix')
int get dateUploadedUnix;
Map<String, dynamic> get json => serializers.serializeWith(serializer, this) as Map<String, dynamic>;
static Serializer<Movie> get serializer => _$movieSerializer;
}
| 0 |
mirrored_repositories/Flutter-Course/lib/src/04 | mirrored_repositories/Flutter-Course/lib/src/04/models/serializers.dart | import 'package:built_collection/built_collection.dart';
import 'package:built_value/serializer.dart';
import 'package:built_value/standard_json_plugin.dart';
import 'package:flutter_course/src/04/models/movie.dart';
part 'serializers.g.dart';
@SerializersFor(<Type>[Movie])
Serializers serializers = (_$serializers.toBuilder() //
..addPlugin(StandardJsonPlugin()))
.build();
| 0 |
mirrored_repositories/Flutter-Course/lib/src/04 | mirrored_repositories/Flutter-Course/lib/src/04/models/movie.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'movie.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<Movie> _$movieSerializer = new _$MovieSerializer();
class _$MovieSerializer implements StructuredSerializer<Movie> {
@override
final Iterable<Type> types = const [Movie, _$Movie];
@override
final String wireName = 'Movie';
@override
Iterable<Object?> serialize(Serializers serializers, Movie object, {FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[
'id',
serializers.serialize(object.id, specifiedType: const FullType(int)),
'url',
serializers.serialize(object.url, specifiedType: const FullType(String)),
'imdb_code',
serializers.serialize(object.imdbCode, specifiedType: const FullType(String)),
'title',
serializers.serialize(object.title, specifiedType: const FullType(String)),
'title_english',
serializers.serialize(object.titleEnglish, specifiedType: const FullType(String)),
'title_long',
serializers.serialize(object.titleLong, specifiedType: const FullType(String)),
'slug',
serializers.serialize(object.slug, specifiedType: const FullType(String)),
'year',
serializers.serialize(object.year, specifiedType: const FullType(int)),
'rating',
serializers.serialize(object.rating, specifiedType: const FullType(num)),
'runtime',
serializers.serialize(object.runtime, specifiedType: const FullType(int)),
'genres',
serializers.serialize(object.genres, specifiedType: const FullType(BuiltList, const [const FullType(String)])),
'summary',
serializers.serialize(object.summary, specifiedType: const FullType(String)),
'description_full',
serializers.serialize(object.descriptionFull, specifiedType: const FullType(String)),
'synopsis',
serializers.serialize(object.synopsis, specifiedType: const FullType(String)),
'yt_trailer_code',
serializers.serialize(object.ytTrailerCode, specifiedType: const FullType(String)),
'language',
serializers.serialize(object.language, specifiedType: const FullType(String)),
'mpa_rating',
serializers.serialize(object.mpaRating, specifiedType: const FullType(String)),
'background_image',
serializers.serialize(object.backgroundImage, specifiedType: const FullType(String)),
'background_image_original',
serializers.serialize(object.backgroundImageOriginal, specifiedType: const FullType(String)),
'small_cover_image',
serializers.serialize(object.smallCoverImage, specifiedType: const FullType(String)),
'medium_cover_image',
serializers.serialize(object.mediumCoverImage, specifiedType: const FullType(String)),
'large_cover_image',
serializers.serialize(object.largeCoverImage, specifiedType: const FullType(String)),
'state',
serializers.serialize(object.state, specifiedType: const FullType(String)),
'date_uploaded',
serializers.serialize(object.dateUploaded, specifiedType: const FullType(String)),
'date_uploaded_unix',
serializers.serialize(object.dateUploadedUnix, specifiedType: const FullType(int)),
];
return result;
}
@override
Movie deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new MovieBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'id':
result.id = serializers.deserialize(value, specifiedType: const FullType(int)) as int;
break;
case 'url':
result.url = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'imdb_code':
result.imdbCode = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'title':
result.title = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'title_english':
result.titleEnglish = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'title_long':
result.titleLong = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'slug':
result.slug = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'year':
result.year = serializers.deserialize(value, specifiedType: const FullType(int)) as int;
break;
case 'rating':
result.rating = serializers.deserialize(value, specifiedType: const FullType(num)) as num;
break;
case 'runtime':
result.runtime = serializers.deserialize(value, specifiedType: const FullType(int)) as int;
break;
case 'genres':
result.genres.replace(serializers.deserialize(value,
specifiedType: const FullType(BuiltList, const [const FullType(String)]))! as BuiltList<Object?>);
break;
case 'summary':
result.summary = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'description_full':
result.descriptionFull = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'synopsis':
result.synopsis = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'yt_trailer_code':
result.ytTrailerCode = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'language':
result.language = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'mpa_rating':
result.mpaRating = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'background_image':
result.backgroundImage = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'background_image_original':
result.backgroundImageOriginal =
serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'small_cover_image':
result.smallCoverImage = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'medium_cover_image':
result.mediumCoverImage = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'large_cover_image':
result.largeCoverImage = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'state':
result.state = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'date_uploaded':
result.dateUploaded = serializers.deserialize(value, specifiedType: const FullType(String)) as String;
break;
case 'date_uploaded_unix':
result.dateUploadedUnix = serializers.deserialize(value, specifiedType: const FullType(int)) as int;
break;
}
}
return result.build();
}
}
class _$Movie extends Movie {
@override
final int id;
@override
final String url;
@override
final String imdbCode;
@override
final String title;
@override
final String titleEnglish;
@override
final String titleLong;
@override
final String slug;
@override
final int year;
@override
final num rating;
@override
final int runtime;
@override
final BuiltList<String> genres;
@override
final String summary;
@override
final String descriptionFull;
@override
final String synopsis;
@override
final String ytTrailerCode;
@override
final String language;
@override
final String mpaRating;
@override
final String backgroundImage;
@override
final String backgroundImageOriginal;
@override
final String smallCoverImage;
@override
final String mediumCoverImage;
@override
final String largeCoverImage;
@override
final String state;
@override
final String dateUploaded;
@override
final int dateUploadedUnix;
factory _$Movie([void Function(MovieBuilder)? updates]) => (new MovieBuilder()..update(updates)).build();
_$Movie._(
{required this.id,
required this.url,
required this.imdbCode,
required this.title,
required this.titleEnglish,
required this.titleLong,
required this.slug,
required this.year,
required this.rating,
required this.runtime,
required this.genres,
required this.summary,
required this.descriptionFull,
required this.synopsis,
required this.ytTrailerCode,
required this.language,
required this.mpaRating,
required this.backgroundImage,
required this.backgroundImageOriginal,
required this.smallCoverImage,
required this.mediumCoverImage,
required this.largeCoverImage,
required this.state,
required this.dateUploaded,
required this.dateUploadedUnix})
: super._() {
BuiltValueNullFieldError.checkNotNull(id, 'Movie', 'id');
BuiltValueNullFieldError.checkNotNull(url, 'Movie', 'url');
BuiltValueNullFieldError.checkNotNull(imdbCode, 'Movie', 'imdbCode');
BuiltValueNullFieldError.checkNotNull(title, 'Movie', 'title');
BuiltValueNullFieldError.checkNotNull(titleEnglish, 'Movie', 'titleEnglish');
BuiltValueNullFieldError.checkNotNull(titleLong, 'Movie', 'titleLong');
BuiltValueNullFieldError.checkNotNull(slug, 'Movie', 'slug');
BuiltValueNullFieldError.checkNotNull(year, 'Movie', 'year');
BuiltValueNullFieldError.checkNotNull(rating, 'Movie', 'rating');
BuiltValueNullFieldError.checkNotNull(runtime, 'Movie', 'runtime');
BuiltValueNullFieldError.checkNotNull(genres, 'Movie', 'genres');
BuiltValueNullFieldError.checkNotNull(summary, 'Movie', 'summary');
BuiltValueNullFieldError.checkNotNull(descriptionFull, 'Movie', 'descriptionFull');
BuiltValueNullFieldError.checkNotNull(synopsis, 'Movie', 'synopsis');
BuiltValueNullFieldError.checkNotNull(ytTrailerCode, 'Movie', 'ytTrailerCode');
BuiltValueNullFieldError.checkNotNull(language, 'Movie', 'language');
BuiltValueNullFieldError.checkNotNull(mpaRating, 'Movie', 'mpaRating');
BuiltValueNullFieldError.checkNotNull(backgroundImage, 'Movie', 'backgroundImage');
BuiltValueNullFieldError.checkNotNull(backgroundImageOriginal, 'Movie', 'backgroundImageOriginal');
BuiltValueNullFieldError.checkNotNull(smallCoverImage, 'Movie', 'smallCoverImage');
BuiltValueNullFieldError.checkNotNull(mediumCoverImage, 'Movie', 'mediumCoverImage');
BuiltValueNullFieldError.checkNotNull(largeCoverImage, 'Movie', 'largeCoverImage');
BuiltValueNullFieldError.checkNotNull(state, 'Movie', 'state');
BuiltValueNullFieldError.checkNotNull(dateUploaded, 'Movie', 'dateUploaded');
BuiltValueNullFieldError.checkNotNull(dateUploadedUnix, 'Movie', 'dateUploadedUnix');
}
@override
Movie rebuild(void Function(MovieBuilder) updates) => (toBuilder()..update(updates)).build();
@override
MovieBuilder toBuilder() => new MovieBuilder()..replace(this);
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Movie &&
id == other.id &&
url == other.url &&
imdbCode == other.imdbCode &&
title == other.title &&
titleEnglish == other.titleEnglish &&
titleLong == other.titleLong &&
slug == other.slug &&
year == other.year &&
rating == other.rating &&
runtime == other.runtime &&
genres == other.genres &&
summary == other.summary &&
descriptionFull == other.descriptionFull &&
synopsis == other.synopsis &&
ytTrailerCode == other.ytTrailerCode &&
language == other.language &&
mpaRating == other.mpaRating &&
backgroundImage == other.backgroundImage &&
backgroundImageOriginal == other.backgroundImageOriginal &&
smallCoverImage == other.smallCoverImage &&
mediumCoverImage == other.mediumCoverImage &&
largeCoverImage == other.largeCoverImage &&
state == other.state &&
dateUploaded == other.dateUploaded &&
dateUploadedUnix == other.dateUploadedUnix;
}
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc($jc(0, id.hashCode),
url.hashCode),
imdbCode.hashCode),
title.hashCode),
titleEnglish.hashCode),
titleLong.hashCode),
slug.hashCode),
year.hashCode),
rating.hashCode),
runtime.hashCode),
genres.hashCode),
summary.hashCode),
descriptionFull.hashCode),
synopsis.hashCode),
ytTrailerCode.hashCode),
language.hashCode),
mpaRating.hashCode),
backgroundImage.hashCode),
backgroundImageOriginal.hashCode),
smallCoverImage.hashCode),
mediumCoverImage.hashCode),
largeCoverImage.hashCode),
state.hashCode),
dateUploaded.hashCode),
dateUploadedUnix.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Movie')
..add('id', id)
..add('url', url)
..add('imdbCode', imdbCode)
..add('title', title)
..add('titleEnglish', titleEnglish)
..add('titleLong', titleLong)
..add('slug', slug)
..add('year', year)
..add('rating', rating)
..add('runtime', runtime)
..add('genres', genres)
..add('summary', summary)
..add('descriptionFull', descriptionFull)
..add('synopsis', synopsis)
..add('ytTrailerCode', ytTrailerCode)
..add('language', language)
..add('mpaRating', mpaRating)
..add('backgroundImage', backgroundImage)
..add('backgroundImageOriginal', backgroundImageOriginal)
..add('smallCoverImage', smallCoverImage)
..add('mediumCoverImage', mediumCoverImage)
..add('largeCoverImage', largeCoverImage)
..add('state', state)
..add('dateUploaded', dateUploaded)
..add('dateUploadedUnix', dateUploadedUnix))
.toString();
}
}
class MovieBuilder implements Builder<Movie, MovieBuilder> {
_$Movie? _$v;
int? _id;
int? get id => _$this._id;
set id(int? id) => _$this._id = id;
String? _url;
String? get url => _$this._url;
set url(String? url) => _$this._url = url;
String? _imdbCode;
String? get imdbCode => _$this._imdbCode;
set imdbCode(String? imdbCode) => _$this._imdbCode = imdbCode;
String? _title;
String? get title => _$this._title;
set title(String? title) => _$this._title = title;
String? _titleEnglish;
String? get titleEnglish => _$this._titleEnglish;
set titleEnglish(String? titleEnglish) => _$this._titleEnglish = titleEnglish;
String? _titleLong;
String? get titleLong => _$this._titleLong;
set titleLong(String? titleLong) => _$this._titleLong = titleLong;
String? _slug;
String? get slug => _$this._slug;
set slug(String? slug) => _$this._slug = slug;
int? _year;
int? get year => _$this._year;
set year(int? year) => _$this._year = year;
num? _rating;
num? get rating => _$this._rating;
set rating(num? rating) => _$this._rating = rating;
int? _runtime;
int? get runtime => _$this._runtime;
set runtime(int? runtime) => _$this._runtime = runtime;
ListBuilder<String>? _genres;
ListBuilder<String> get genres => _$this._genres ??= new ListBuilder<String>();
set genres(ListBuilder<String>? genres) => _$this._genres = genres;
String? _summary;
String? get summary => _$this._summary;
set summary(String? summary) => _$this._summary = summary;
String? _descriptionFull;
String? get descriptionFull => _$this._descriptionFull;
set descriptionFull(String? descriptionFull) => _$this._descriptionFull = descriptionFull;
String? _synopsis;
String? get synopsis => _$this._synopsis;
set synopsis(String? synopsis) => _$this._synopsis = synopsis;
String? _ytTrailerCode;
String? get ytTrailerCode => _$this._ytTrailerCode;
set ytTrailerCode(String? ytTrailerCode) => _$this._ytTrailerCode = ytTrailerCode;
String? _language;
String? get language => _$this._language;
set language(String? language) => _$this._language = language;
String? _mpaRating;
String? get mpaRating => _$this._mpaRating;
set mpaRating(String? mpaRating) => _$this._mpaRating = mpaRating;
String? _backgroundImage;
String? get backgroundImage => _$this._backgroundImage;
set backgroundImage(String? backgroundImage) => _$this._backgroundImage = backgroundImage;
String? _backgroundImageOriginal;
String? get backgroundImageOriginal => _$this._backgroundImageOriginal;
set backgroundImageOriginal(String? backgroundImageOriginal) =>
_$this._backgroundImageOriginal = backgroundImageOriginal;
String? _smallCoverImage;
String? get smallCoverImage => _$this._smallCoverImage;
set smallCoverImage(String? smallCoverImage) => _$this._smallCoverImage = smallCoverImage;
String? _mediumCoverImage;
String? get mediumCoverImage => _$this._mediumCoverImage;
set mediumCoverImage(String? mediumCoverImage) => _$this._mediumCoverImage = mediumCoverImage;
String? _largeCoverImage;
String? get largeCoverImage => _$this._largeCoverImage;
set largeCoverImage(String? largeCoverImage) => _$this._largeCoverImage = largeCoverImage;
String? _state;
String? get state => _$this._state;
set state(String? state) => _$this._state = state;
String? _dateUploaded;
String? get dateUploaded => _$this._dateUploaded;
set dateUploaded(String? dateUploaded) => _$this._dateUploaded = dateUploaded;
int? _dateUploadedUnix;
int? get dateUploadedUnix => _$this._dateUploadedUnix;
set dateUploadedUnix(int? dateUploadedUnix) => _$this._dateUploadedUnix = dateUploadedUnix;
MovieBuilder();
MovieBuilder get _$this {
final $v = _$v;
if ($v != null) {
_id = $v.id;
_url = $v.url;
_imdbCode = $v.imdbCode;
_title = $v.title;
_titleEnglish = $v.titleEnglish;
_titleLong = $v.titleLong;
_slug = $v.slug;
_year = $v.year;
_rating = $v.rating;
_runtime = $v.runtime;
_genres = $v.genres.toBuilder();
_summary = $v.summary;
_descriptionFull = $v.descriptionFull;
_synopsis = $v.synopsis;
_ytTrailerCode = $v.ytTrailerCode;
_language = $v.language;
_mpaRating = $v.mpaRating;
_backgroundImage = $v.backgroundImage;
_backgroundImageOriginal = $v.backgroundImageOriginal;
_smallCoverImage = $v.smallCoverImage;
_mediumCoverImage = $v.mediumCoverImage;
_largeCoverImage = $v.largeCoverImage;
_state = $v.state;
_dateUploaded = $v.dateUploaded;
_dateUploadedUnix = $v.dateUploadedUnix;
_$v = null;
}
return this;
}
@override
void replace(Movie other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$Movie;
}
@override
void update(void Function(MovieBuilder)? updates) {
if (updates != null) updates(this);
}
@override
_$Movie build() {
_$Movie _$result;
try {
_$result = _$v ??
new _$Movie._(
id: BuiltValueNullFieldError.checkNotNull(id, 'Movie', 'id'),
url: BuiltValueNullFieldError.checkNotNull(url, 'Movie', 'url'),
imdbCode: BuiltValueNullFieldError.checkNotNull(imdbCode, 'Movie', 'imdbCode'),
title: BuiltValueNullFieldError.checkNotNull(title, 'Movie', 'title'),
titleEnglish: BuiltValueNullFieldError.checkNotNull(titleEnglish, 'Movie', 'titleEnglish'),
titleLong: BuiltValueNullFieldError.checkNotNull(titleLong, 'Movie', 'titleLong'),
slug: BuiltValueNullFieldError.checkNotNull(slug, 'Movie', 'slug'),
year: BuiltValueNullFieldError.checkNotNull(year, 'Movie', 'year'),
rating: BuiltValueNullFieldError.checkNotNull(rating, 'Movie', 'rating'),
runtime: BuiltValueNullFieldError.checkNotNull(runtime, 'Movie', 'runtime'),
genres: genres.build(),
summary: BuiltValueNullFieldError.checkNotNull(summary, 'Movie', 'summary'),
descriptionFull: BuiltValueNullFieldError.checkNotNull(descriptionFull, 'Movie', 'descriptionFull'),
synopsis: BuiltValueNullFieldError.checkNotNull(synopsis, 'Movie', 'synopsis'),
ytTrailerCode: BuiltValueNullFieldError.checkNotNull(ytTrailerCode, 'Movie', 'ytTrailerCode'),
language: BuiltValueNullFieldError.checkNotNull(language, 'Movie', 'language'),
mpaRating: BuiltValueNullFieldError.checkNotNull(mpaRating, 'Movie', 'mpaRating'),
backgroundImage: BuiltValueNullFieldError.checkNotNull(backgroundImage, 'Movie', 'backgroundImage'),
backgroundImageOriginal:
BuiltValueNullFieldError.checkNotNull(backgroundImageOriginal, 'Movie', 'backgroundImageOriginal'),
smallCoverImage: BuiltValueNullFieldError.checkNotNull(smallCoverImage, 'Movie', 'smallCoverImage'),
mediumCoverImage: BuiltValueNullFieldError.checkNotNull(mediumCoverImage, 'Movie', 'mediumCoverImage'),
largeCoverImage: BuiltValueNullFieldError.checkNotNull(largeCoverImage, 'Movie', 'largeCoverImage'),
state: BuiltValueNullFieldError.checkNotNull(state, 'Movie', 'state'),
dateUploaded: BuiltValueNullFieldError.checkNotNull(dateUploaded, 'Movie', 'dateUploaded'),
dateUploadedUnix: BuiltValueNullFieldError.checkNotNull(dateUploadedUnix, 'Movie', 'dateUploadedUnix'));
} catch (_) {
late String _$failedField;
try {
_$failedField = 'genres';
genres.build();
} catch (e) {
throw new BuiltValueNestedFieldError('Movie', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/Flutter-Course/lib/src | mirrored_repositories/Flutter-Course/lib/src/03/basic_phrases.dart | import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(const BasicPhrases());
}
class BasicPhrases extends StatefulWidget {
const BasicPhrases({Key? key}) : super(key: key);
@override
_BasicPhrasesState createState() => _BasicPhrasesState();
}
class _BasicPhrasesState extends State<BasicPhrases> {
String tmpFileURL = '';
int currentIndex = -1;
List<String> content = <String>[
'Rum Rum',
'Rum Rum(in France)',
'Beep Beep',
'Beep Beep(in France)',
'Ciu Ciu',
'Ciu Ciu(in France)',
'Ciu Ciu(Magyar )',
'Ciu Ciu(Russ)'
];
List<String> tempFileURLs = <String>[];
AudioPlayer player = AudioPlayer();
Future<void> addSounds() async {
final Directory temp = await getTemporaryDirectory();
ByteData data;
for (int i = 0; i < 8; i++) {
final File tmpFile = File('${temp.path}/$i.mp3');
final String path = 'audioAss/$i.mp3';
data = await rootBundle.load(path);
await tmpFile.writeAsBytes(data.buffer.asUint8List(), flush: true);
tmpFileURL = tmpFile.uri.toString();
tempFileURLs.add(tmpFileURL);
}
}
void _playSound() {
tmpFileURL = tempFileURLs[currentIndex];
player.play(tmpFileURL);
}
@override
void initState() {
super.initState();
addSounds();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('Basic Phrases'),
),
body: GridView.builder(
itemCount: content.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 32.0,
mainAxisSpacing: 32.0,
),
itemBuilder: (BuildContext context, int index) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(23),
gradient: const LinearGradient(
colors: <MaterialColor>[
Colors.red,
Colors.green,
Colors.yellow,
],
begin: FractionalOffset.centerLeft,
end: FractionalOffset.centerRight,
),
),
child: TextButton(
child: Text(content[index], style: const TextStyle(color: Colors.black54)),
onPressed: () {
setState(() {
currentIndex = index;
_playSound();
});
},
),
);
}),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Course/lib/src | mirrored_repositories/Flutter-Course/lib/src/03/tic_tac_toe.dart | import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
home: TicTac(),
));
}
class TicTac extends StatefulWidget {
const TicTac({Key? key}) : super(key: key);
@override
_TicTacState createState() => _TicTacState();
}
class PositionTicTacToe {
PositionTicTacToe(this.used, this.color, this.val);
int used;
Color? color;
ValidationPoss val;
}
class ValidationPoss {
ValidationPoss(this.pos1, this.pos2, this.pos3);
int pos1 = 0;
int pos2 = 0;
int pos3 = 0;
}
class _TicTacState extends State<TicTac> {
List<PositionTicTacToe> content =
List<PositionTicTacToe>.generate(9, (_) => PositionTicTacToe(0, Colors.white, ValidationPoss(0, 0, 0)));
List<ValidationPoss> valPos = <ValidationPoss>[
ValidationPoss(0, 1, 2),
ValidationPoss(3, 4, 5),
ValidationPoss(6, 7, 8),
ValidationPoss(0, 3, 6),
ValidationPoss(1, 4, 7),
ValidationPoss(2, 5, 8),
ValidationPoss(0, 4, 8),
ValidationPoss(2, 4, 6),
];
int countDraw = 0;
int personToMove = 1;
int endGame = 0;
PositionTicTacToe? isEnd() {
for (int i = 0; i < valPos.length; i++) {
if (content[valPos[i].pos1].color == content[valPos[i].pos2].color &&
content[valPos[i].pos2].color == content[valPos[i].pos3].color)
return PositionTicTacToe(0, content[valPos[i].pos3].color, valPos[i]);
}
return (countDraw == 9)
? PositionTicTacToe(0, Colors.pink, ValidationPoss(0, 0, 0))
: PositionTicTacToe(0, null, ValidationPoss(0, 0, 0));
}
bool resetAtWon(PositionTicTacToe whoWon) {
for (int i = 0; i < content.length; i++) {
if (i != whoWon.val.pos1 && i != whoWon.val.pos2 && i != whoWon.val.pos3) {
content[i].color = Colors.white;
content[i].used = 0;
}
}
return true;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
'TicTacToe',
style: TextStyle(color: Colors.black),
),
centerTitle: true,
backgroundColor: Colors.yellow,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
GridView.builder(
shrinkWrap: true,
itemCount: 9,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemBuilder: (BuildContext context, int index) {
return Item(
backColor: content[index].color,
onTap: () {
setState(() {
if (personToMove == 1 && content[index].used == 0) {
content[index].color = Colors.green;
content[index].used = 1;
personToMove = 0;
countDraw++;
} else if (content[index].used == 0) {
content[index].color = Colors.red;
content[index].used = 1;
personToMove = 1;
countDraw++;
}
final PositionTicTacToe? outEnd = isEnd();
if (outEnd!.color != null) {
if (outEnd.color == Colors.green || outEnd.color == Colors.red) {
endGame = 1;
resetAtWon(outEnd);
} else if (outEnd.color == Colors.pink) {
endGame = 1;
}
}
});
},
);
}),
if (endGame == 1)
Padding(
padding: const EdgeInsets.all(16.0),
child: TextButton(
onPressed: () {
setState(() {
resetAtWon(PositionTicTacToe(0, null, ValidationPoss(-1, -1, -1)));
endGame = 0;
personToMove = 1;
countDraw = 0;
});
},
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Play Again!',
style: TextStyle(color: Colors.black),
),
),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.grey),
),
),
)
],
));
}
}
typedef OnTap = void Function();
class Item extends StatelessWidget {
const Item({Key? key, required this.onTap, required this.backColor}) : super(key: key);
final Color? backColor;
final OnTap onTap;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
onTap();
},
child: AnimatedContainer(
decoration:
BoxDecoration(borderRadius: BorderRadius.zero, border: Border.all(color: Colors.black), color: backColor),
duration: const Duration(milliseconds: 300),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Course | mirrored_repositories/Flutter-Course/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_course/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/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/lib/default_payment.dart | import 'package:bootpay/bootpay.dart';
import 'package:bootpay/model/extra.dart';
import 'package:bootpay/model/item.dart';
import 'package:bootpay/model/payload.dart';
import 'package:bootpay/model/stat_item.dart';
import 'package:bootpay/model/user.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class DefaultPayment extends StatefulWidget {
// You can ask Get to find a Controller that is being used by another page and redirect you to it.
DefaultPayment({Key? key, required this.name}) : super(key: key);
final String name;
@override
State<DefaultPayment> createState() => _DefaultPaymentState();
}
class _DefaultPaymentState extends State<DefaultPayment> {
String webApplicationId = '5b8f6a4d396fa665fdc2b5e7';
String androidApplicationId = '5b8f6a4d396fa665fdc2b5e8';
String iosApplicationId = '63030a85d01c7e001af64359';
@override
Widget build(context) {
// Access the updated count variable
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.black,
toolbarHeight: 70,
// appBar 높이 70
elevation: 0,
// 음영 0
title: InkWell(
onTap: () {},
child: Text('${widget.name} 결제창',
style: TextStyle(
color: Colors.white,
fontSize: 22.0,
fontWeight: FontWeight.bold))),
),
body: SafeArea(
child: Center(
child: TextButton(
onPressed: () => bootpayTest(context),
child: const Text('PG일반 결제 테스트', style: TextStyle(fontSize: 16.0))
)
)
)
);
}
void bootpayTest(BuildContext context) {
Payload payload = getPayload();
if(kIsWeb) {
payload.extra?.openType = "iframe";
}
Bootpay().requestPayment(
context: context,
payload: payload,
showCloseButton: false,
// closeButton: Icon(Icons.close, size: 35.0, color: Colors.black54),
onCancel: (String data) {
print('------- onCancel: $data');
},
onError: (String data) {
print('------- onCancel: $data');
},
onClose: () {
print('------- onClose');
Bootpay().dismiss(context); //명시적으로 부트페이 뷰 종료 호출
//TODO - 원하시는 라우터로 페이지 이동
},
onIssued: (String data) {
print('------- onIssued: $data');
},
onConfirm: (String data) {
/**
1. 바로 승인하고자 할 때
return true;
**/
/***
2. 클라이언트 승인 하고자 할 때
Bootpay().transactionConfirm();
return false;
***/
/***
3. 서버승인을 하고자 하실 때 (클라이언트 승인 X)
return false; 후에 서버에서 결제승인 수행
*/
Bootpay().transactionConfirm();
return false;
},
onDone: (String data) {
print('------- onDone: $data');
},
);
}
Payload getPayload() {
Payload payload = Payload();
Item item1 = Item();
item1.name = "미키 '마우스"; // 주문정보에 담길 상품명
item1.qty = 1; // 해당 상품의 주문 수량
item1.id = "ITEM_CODE_MOUSE"; // 해당 상품의 고유 키
item1.price = 500; // 상품의 가격
Item item2 = Item();
item2.name = "키보드"; // 주문정보에 담길 상품명
item2.qty = 1; // 해당 상품의 주문 수량
item2.id = "ITEM_CODE_KEYBOARD"; // 해당 상품의 고유 키
item2.price = 500; // 상품의 가격
List<Item> itemList = [item1, item2];
payload.webApplicationId = webApplicationId; // web application id
payload.androidApplicationId = androidApplicationId; // android application id
payload.iosApplicationId = iosApplicationId; // ios application id
payload.pg = '나이스페이';
payload.method = '카드';
// payload.methods = ['card', 'phone', 'vbank', 'bank', 'kakao'];
payload.orderName = "테스트 상품"; //결제할 상품명
payload.price = 1000.0; //정기결제시 0 혹은 주석
payload.orderId = DateTime.now().millisecondsSinceEpoch.toString(); //주문번호, 개발사에서 고유값으로 지정해야함
payload.metadata = {
"callbackParam1" : "value12",
"callbackParam2" : "value34",
"callbackParam3" : "value56",
"callbackParam4" : "value78",
}; // 전달할 파라미터, 결제 후 되돌려 주는 값
payload.items = itemList; // 상품정보 배열
User user = User(); // 구매자 정보
user.username = "사용자 이름";
user.email = "[email protected]";
user.area = "서울";
user.phone = "010-4033-4678";
user.addr = '서울시 동작구 상도로 222';
Extra extra = Extra(); // 결제 옵션
extra.appScheme = 'bootpayFlutterExample';
extra.cardQuota = '3';
// extra.openType = 'popup';
// extra.carrier = "SKT,KT,LGT"; //본인인증 시 고정할 통신사명
// extra.ageLimit = 20; // 본인인증시 제한할 최소 나이 ex) 20 -> 20살 이상만 인증이 가능
payload.user = user;
payload.extra = extra;
return payload;
}
} | 0 |
mirrored_repositories/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/lib/db.dart | import 'dart:async';
import 'dart:io';
import 'module.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
// Sqflite 데이터베이스 연동, sql 주입
class DatabaseHelper {
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database;
Future<Database> get database async => _database ??= await _initDatabase();
Future<Database> _initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'groceries.db');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE groceries(
id INTEGER PRIMARY KEY,
name TEXT
)
''');
}
Future<int> remove(int id) async {
Database db = await instance.database;
return await db.delete('groceries', where: 'id = ?', whereArgs: [id]);
}
Future<int> update(Menu grocery) async {
Database db = await instance.database;
return await db.update('groceries', grocery.toMap(),
where: 'id = ?', whereArgs: [grocery.id]);
}
Future<List<Menu>> getGroceries() async {
Database db = await instance.database;
var groceries = await db.query('groceries', orderBy: 'name');
List<Menu> groceryList = groceries.isNotEmpty
? groceries.map((c) => Menu.fromMap(c)).toList()
: [];
return groceryList;
}
Future<int> add(Menu grocery) async {
Database db = await instance.database;
return await db.insert('groceries', grocery.toMap());
}
} | 0 |
mirrored_repositories/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/lib/menuPayment.dart | import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:restaurant_order/default_payment.dart';
class menuPayment extends StatefulWidget {
menuPayment({Key? key, required this.name}) : super(key: key);
final String name;
@override
State<menuPayment> createState() => _menuPaymentState();
}
class _menuPaymentState extends State<menuPayment> {
int? selectedId;
final textController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.black,
toolbarHeight: 70,
// appBar 높이 70
elevation: 0,
// 음영 0
title: InkWell(
onTap: () {print(widget.name);},
child: Text("${widget.name} 주문 페이지",
style: TextStyle(
color: Colors.white,
fontSize: 22.0,
fontWeight: FontWeight.bold))),
),
body: SingleChildScrollView(
child: Column(
children: [
Stack(
children: [
Positioned(
child: Image.asset('./asset/img/food2.jpeg',
height: 200, fit: BoxFit.cover),
),
],
),
SizedBox(
height:20,
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'가격',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
Text(
'21,000원',
style:TextStyle(fontSize:30, fontWeight:FontWeight.bold),
)
],
),
),
SizedBox(
height:30,
),
Container(
child: Text('고소하고 담백한 맛의 치킨입니다.', style:TextStyle(fontSize:20,)),
),
SizedBox(
height:190,
),
Padding(
padding: const EdgeInsets.only(left:15.0),
child: Container( // 결제 창 이동
child:Row(
children:[
Padding(
padding: const EdgeInsets.only(right:15.0),
child: Column(
children: [
Text('배달최소금액', style:TextStyle(fontSize:20.0,color: Colors.grey[600])),
Text('11,000원', style:TextStyle(fontSize:20.0,)),
],
),
),
ElevatedButton(
onPressed: () => Get.to(DefaultPayment(name:widget.name)),
child: Padding(
padding: const EdgeInsets.only(top:10.0, bottom:10.0, right:15, left:15,),
child: Text('21,000원 결제', style:TextStyle(fontSize:30,)),
),
)
]
)
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/lib/module.dart | import 'package:flutter/material.dart';
// 메뉴 클래스
class Menu {
final int? id; // 식별자
final String name; // 메뉴 이름
Menu({this.id, required this.name});
factory Menu.fromMap(Map<String, dynamic> json) => new Menu(
id: json['id'],
name: json['name'],
);
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
};
}
} | 0 |
mirrored_repositories/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/lib/ManagementScreen.dart | import 'package:path/path.dart';
import 'package:restaurant_order/MainScreen.dart';
import 'package:restaurant_order/login.dart';
import 'package:restaurant_order/menuAdd.dart';
import 'db.dart';
import 'module.dart';
import 'package:flutter/material.dart';
// 관리자 로그인 후 시스템 메인 화면
class ManagementScreen extends StatefulWidget {
@override
_ManagementScreenState createState() => _ManagementScreenState();
}
class _ManagementScreenState extends State<ManagementScreen> {
int? selectedId;
final textController = TextEditingController();
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusManager.instance.primaryFocus?.unfocus(); // 키보드 닫기 이벤트
},
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.black,
toolbarHeight: 70,
// appBar 높이 70
elevation: 0,
// 음영 0
title: InkWell(
onTap: () {},
child: Text('5조 레스토랑 시스템 관리자 화면',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold))),
actions: [
// 오른쪽 아이콘 위젯들
Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: Padding(
padding: EdgeInsets.only(
right: 20,
),
child: IconButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Login()));
},
icon: Icon(Icons.account_circle_rounded,
color: Colors.white, size: 30),
),
),
),
],
),
],
),
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 40,
),
ElevatedButton(
// 로그아웃 버튼
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => MainScreen()));
},
child: Text('로그아웃',
style:
TextStyle(fontSize: 30, fontWeight: FontWeight.bold)),
),
TextField(
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
controller: textController,
decoration: InputDecoration(
labelText: '수정할 메뉴 이름이 여기에 표시됩니다.',
labelStyle: TextStyle(
fontSize: 25,
)),
),
SizedBox(
height: 10,
),
ElevatedButton(
child: Text('메뉴 수정하기',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
)),
onPressed: () async {
await DatabaseHelper.instance.update(
Menu(id: selectedId, name: textController.text),
);
setState(() {
textController.clear();
selectedId = null;
});
FocusManager.instance.primaryFocus?.unfocus(); // 키보드 닫기 이벤트
},
),
SizedBox(
height: 40,
),
ElevatedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => menuAdd()))
.then((value) {
setState(() {});
});
},
child: Text('메뉴 등록하기',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
))),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text('판매 중인 메뉴 목록',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
)),
),
SizedBox(
height: 40,
),
FutureBuilder<List<Menu>>(
future: DatabaseHelper.instance.getGroceries(),
builder:
(BuildContext context, AsyncSnapshot<List<Menu>> snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text('Loading',
style: TextStyle(
fontSize: 23,
)),
);
}
return snapshot.data!.isEmpty
? Center(
child: Text('판매 중인 상품 목록이 비어있습니다.',
style: TextStyle(
fontSize: 25, fontWeight: FontWeight.bold)),
)
: ListView(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
children: snapshot.data!.map((menu) {
return Center(
child: Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.grey.shade500,
),
borderRadius: BorderRadius.circular(15.0),
),
color: selectedId == menu.id
? Colors.white70
: Colors.white,
child: ListTile(
onTap: () {
setState(() {
if (selectedId == null) {
textController.text = menu.name;
selectedId = menu.id;
} else {
textController.text = '';
selectedId = null;
}
});
},
contentPadding: EdgeInsets.symmetric(
vertical: 20.0, horizontal: 16.0),
leading: Container(
width: 100,
height: 600,
child: Image.asset('./asset/img/food2.jpeg',
height: 200, fit: BoxFit.fill),
),
title: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(menu.name,
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold)),
IconButton(
icon: Icon(Icons.delete, size: 30),
onPressed: () {
setState(() {
DatabaseHelper.instance
.remove(menu.id!);
});
},
),
],
),
),
),
);
}).toList(),
);
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/lib/login.dart | import 'package:flutter/material.dart';
import 'package:restaurant_order/ManagementScreen.dart';
import 'package:restaurant_order/main.dart';
import 'package:restaurant_order/MainScreen.dart';
// 관리자 로그인 화면
class Login extends StatefulWidget {
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
final _formKey = GlobalKey<FormState>(); // 폼의 상태를 얻기 위한 키
final _idController = TextEditingController(); // 아이디 컨트롤러 객체
final _passwordController = TextEditingController(); // 패스워드 컨트롤러 객체
@override
void dispose() {
_idController.dispose(); // 다 사용한 컨트롤러 해제
_passwordController.dispose(); // 다 사용한 컨트롤러 해제
super.dispose();
}
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.black,
title: Text('시스템 관리자 로그인 페이지', style:TextStyle(fontSize:23, fontWeight:FontWeight.bold)),
),
body: SingleChildScrollView(
child: Container(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey, // 키 할당
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
right: 230.0,
top: 30,
bottom: 30,
),
child: Text('Login',
style:
TextStyle(fontSize: 40, fontWeight: FontWeight.bold)),
),
TextFormField(
decoration: InputDecoration(
// 외곽선이 있고 힌트로 '아이디'를 표시
border: OutlineInputBorder(),
hintText: '시스템 관리자 ID를 입력하세요', // placeholder 아이디
),
controller: _idController, // 키 컨트롤러 연결
validator: (value) {
if (value!.trim().isEmpty) {
return '아이디를 입력해 주세요';
}
return null;
},
),
SizedBox(
height: 16.0,
),
TextFormField(
decoration: InputDecoration(
// 외곽선이 있고 힌트로 '비밀번호'를 표시
border: OutlineInputBorder(),
hintText: '시스템 관리자 비밀번호를 입력하세요', // placeholder 비밀번호
),
controller: _passwordController,
keyboardType: TextInputType.number, // 숫자만 입력할 수 있음
validator: (value) {
if (value!.trim().isEmpty) {
return '비밀번호를 입력하세요';
}
return null;
},
),
Container(
// 버튼 여백,배치
margin: const EdgeInsets.only(top: 16.0), // 위 쪽에만 16크기의 여백
alignment: Alignment.centerRight, // 오른쪽 가운데에 위치
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate() &&
_idController.text == "원치현" &&
_passwordController.text == "1234") {
// 아이디와 비밀번호 값이 검증되었다면 화면 이동
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ManagementScreen()),
);
}
},
child: Text('로그인',
style: TextStyle(
fontSize: 30,
)),
),
)
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/lib/menuAdd.dart | import 'package:path/path.dart';
import 'package:restaurant_order/MainScreen.dart';
import 'db.dart';
import 'module.dart';
import 'package:flutter/material.dart';
// 메뉴 등록하기 클래스
class menuAdd extends StatefulWidget {
@override
_menuAddState createState() => _menuAddState();
}
class _menuAddState extends State<menuAdd> {
int? selectedId;
final textController = TextEditingController();
@override
void initState() {
// TODO: implement initState
super.initState();
setState(() {
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusManager.instance.primaryFocus?.unfocus(); // 키보드 닫기 이벤트
},
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
title: Text('신규 메뉴 등록 페이지'),
),
backgroundColor: Colors.white,
body: TextField(
style:TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
controller: textController,
decoration: InputDecoration(
labelText:'등록할 메뉴의 이름을 입력해주세요',
labelStyle:TextStyle(fontSize:25,),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
selectedId != null
? await DatabaseHelper.instance.update(
Menu(id: selectedId, name: textController.text),
)
: await DatabaseHelper.instance.add(
Menu(name: textController.text),
);
Navigator.pop(context, true);
setState(() {
textController.clear();
selectedId = null;
});
},
child: Icon(Icons.add),
),
),
);
}
}
| 0 |
mirrored_repositories/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/lib/main.dart | import 'package:flutter/material.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:restaurant_order/MainScreen.dart';
void main() {
runApp(const MyApp());
}
// 처음 시작하는 화면
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: MainScreen(),
);
}
}
| 0 |
mirrored_repositories/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/lib/MainScreen.dart | import 'package:path/path.dart';
import 'package:restaurant_order/login.dart';
import 'package:restaurant_order/menuAdd.dart';
import 'package:restaurant_order/menuPayment.dart';
import 'db.dart';
import 'module.dart';
import 'package:flutter/material.dart';
class MainScreen extends StatefulWidget {
@override
_MainScreenState createState() => _MainScreenState();
}
// 로그인 전 시스템 메인 화면
class _MainScreenState extends State<MainScreen> {
int? selectedId;
final textController = TextEditingController();
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusManager.instance.primaryFocus?.unfocus(); // 키보드 닫기 이벤트
},
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.black,
toolbarHeight: 70,
// appBar 높이 70
elevation: 0,
// 음영 0
title: InkWell(
onTap: () {},
child: Text('5조 레스토랑 시스템메인 화면',
style: TextStyle(
color: Colors.white,
fontSize: 22.0,
fontWeight: FontWeight.bold))),
actions: [
// 오른쪽 아이콘 위젯들
Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: Padding(
padding: EdgeInsets.only(
right: 20,
),
child: IconButton( // 시스템 관리자 로그인 버튼
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Login()));
},
icon: Icon(Icons.account_circle_rounded,
color: Colors.white, size: 30),
),
),
),
],
),
],
),
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height:20,
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text('판매 중인 메뉴 목록',
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold,
)),
),
SizedBox(
height:40,
),
FutureBuilder<List<Menu>>(
future: DatabaseHelper.instance.getGroceries(),
builder: (BuildContext context,
AsyncSnapshot<List<Menu>> snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text('Loading', style:TextStyle(fontSize:23,)),
);
}
return snapshot.data!.isEmpty
? Center(
child: Text('판매 중인 상품 목록이 비어있습니다.',
style: TextStyle(
fontSize: 25, fontWeight: FontWeight.bold)),
)
: ListView(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
children: snapshot.data!.map((module) {
return Center(
child: Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.grey.shade500,
),
borderRadius: BorderRadius.circular(15.0),
),
color: selectedId == module.id
? Colors.white70
: Colors.white,
child: ListTile(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => menuPayment(name: textController.text)));
setState(() {
if (selectedId == null) {
textController.text = module.name;
selectedId = module.id;
} else {
textController.text = module.name;
selectedId = null;
}
});
},
contentPadding: EdgeInsets.symmetric(
vertical: 20.0, horizontal: 16.0),
leading: Container(
width: 100,
height: 600,
child: Image.asset('./asset/img/food2.jpeg',
height:200,
fit: BoxFit.fill),
),
title: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(module.name, style:TextStyle(fontSize:20, fontWeight:FontWeight.bold)),
],
),
),
)
,
);
}).toList(),
);
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Restaurant_Order_System | mirrored_repositories/Restaurant_Order_System/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 in the flutter_test package. 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:restaurant_order/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/the_task_clone | mirrored_repositories/the_task_clone/lib/home_page.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
final List<Map> myCards =
List.generate(4, (index) => {"id": index, "name": "My task $index"})
.toList();
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
MediaQueryData mediaQueryData = MediaQuery.of(context);
var size = mediaQueryData.size;
return Scaffold(
resizeToAvoidBottomInset: true,
body: CustomScrollView(slivers: [
SliverAppBar(
elevation: 0,
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Icon(Icons.search),
],
),
],
flexibleSpace: FlexibleSpaceBar(
background: Container(
color: Colors.white,
child: const Material(
color: Colors.orange,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(40),
bottomLeft: Radius.circular(40)),
),
),
title: Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
width: size.height * 0.078,
height: size.height * 0.078,
decoration: const BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: [
Colors.orange,
Colors.orange,
Colors.red,
Colors.red
],
begin: Alignment.topLeft,
),
),
child: Container(
margin: const EdgeInsets.all(6.0),
decoration: const BoxDecoration(),
child: const CircleAvatar(
backgroundImage: NetworkImage(
"https://i.ytimg.com/vi/KbW6MdfefNg/oar2.jpg?sqp=-oaymwEVCJUDENAFSFryq4qpAwcIARUAAIhC&rs=AOn4CLCYIc3vcFJeUdzfteDUzzolUHyZFg"),
radius: 30,
),
),
),
const SizedBox(
width: 6,
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Aysenem Yusupova",
style: TextStyle(fontSize: size.width * 0.04),
),
Text(
"Project Manager",
style: TextStyle(fontSize: size.width * 0.04),
),
],
),
],
),
),
pinned: true,
leading: const Icon(Icons.density_medium),
expandedHeight: size.height * 0.270,
backgroundColor: Colors.orange,
systemOverlayStyle:
const SystemUiOverlayStyle(statusBarColor: Colors.black12),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Column(
children: [
Row(
children: [
const Text(
"MyTasks",
style:
TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
const Spacer(),
SizedBox(
height: 80,
width: 80,
child: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.teal,
child: const Icon(
Icons.calendar_today_outlined,
size: 36,
),
))
],
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
FloatingActionButton(
backgroundColor: Colors.red,
onPressed: () {},
child: const Icon(Icons.timer_outlined),
),
const Padding(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"To do",
style: TextStyle(fontSize: 20),
),
Text("5 task now 1-started")
],
),
)
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
FloatingActionButton(
backgroundColor:
const Color.fromARGB(255, 215, 106, 10),
onPressed: () {},
child: const Icon(Icons.timer_outlined),
),
const Padding(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"To do",
style: TextStyle(fontSize: 20),
),
Text("5 task now 1-started")
],
),
)
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
FloatingActionButton(
onPressed: () {},
child: Icon(Icons.timer_outlined),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"To do",
style: TextStyle(fontSize: 20),
),
Text("5 task now 1-started")
],
),
)
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
FloatingActionButton(
backgroundColor: Color.fromARGB(255, 215, 106, 10),
onPressed: () {},
child: Icon(Icons.timer_outlined),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"To do",
style: TextStyle(fontSize: 20),
),
Text("5 task now 1-started")
],
),
),
],
),
),
]),
),
),
SliverGrid.count(
crossAxisCount: 2,
mainAxisSpacing: 4.0,
crossAxisSpacing: 3.0,
childAspectRatio: 0.8,
children: [
MyGrid(
Colors.teal,
const Text(
"Daryo uz",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.white),
),
const Text(
"9 hours progress",
style: TextStyle(color: Colors.white),
),
const Text("25 %",
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
0.25),
MyGrid(
Colors.redAccent,
const Text(
"NeedFood app",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.white),
),
const Text("40 hours progress",
style: TextStyle(color: Colors.white)),
const Text(
"75 %",
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
0.75),
MyGrid(
Colors.orangeAccent,
const Text(
"The task app",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.white),
),
const Text("18 hours progress",
style: TextStyle(color: Colors.white)),
const Text("60 %",
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold)),
0.60),
MyGrid(
Colors.blueAccent,
const Text(
"LAdy Taxi app",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.white),
),
const Text("18 hours progress",
style: TextStyle(color: Colors.white)),
const Text("48 %",
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold)),
0.48),
],
),
],
),
);
}
}
Widget MyConytener(Color color, Text text, Text text2, Icon icon){
return Row(
children: [
SizedBox(
height: 50,
width: 50,
child: Material(
color: color,
borderRadius: BorderRadius.circular(100),
child: icon,
),
),
const SizedBox(
width: 12,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [text, text2],
),
],
);
}
Widget MyGrid(Color color, Text text, Text text2, Text prisend, double int) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 160,
height: 240,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(34),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CircularPercentIndicator(
radius: 30,
center: prisend,
percent: int,
backgroundColor: Colors.black12,
progressColor: Colors.white,
),
const Spacer(),
text,
text2,
],
),
),
);
}
| 0 |
mirrored_repositories/the_task_clone | mirrored_repositories/the_task_clone/lib/main.dart | import 'package:flutter/material.dart';
import 'package:the_task/home_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
| 0 |
mirrored_repositories/the_task_clone | mirrored_repositories/the_task_clone/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 in the flutter_test package. 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:the_task/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/Flare | mirrored_repositories/Flare/lib/HomeScreen.dart | import 'package:beamer/beamer.dart';
import 'package:flare/core/widgets/home_chapter_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:flare/routes/app_route_names.dart';
class Chapter {
String name;
String route;
Chapter({required this.name, required this.route});
}
class HomeScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return HomeScreenState();
}
}
class HomeScreenState extends State<HomeScreen> {
final List<Chapter> entries = <Chapter>[
Chapter(name: "UI Component - AppBar", route: AppRoutes.uiComponentAppBar),
Chapter(name: "UI Component - BottomNavBar", route: AppRoutes.uiComponentBottomNavigationBar),
Chapter(name: "UI Component - Text & FormField", route: AppRoutes.uiComponentTextFormField),
Chapter(name: "UI Component - Buttons", route: AppRoutes.uiComponentButton),
Chapter(name: "UI Component - Drawer", route: AppRoutes.uiComponentDrawer),
Chapter(name: "UI Component - TabBar", route: AppRoutes.uiComponentTabBar),
Chapter(name: "UI Component - Dialogs & Alerts", route: AppRoutes.uiComponentDialogs),
Chapter(name: "UI Component - Card & List Tile & Chip", route: AppRoutes.uiComponentCards),
Chapter(name: "Bloc - Simple HTTP Api Call", route: AppRoutes.bloc),
Chapter(name: "Localizations - EN/ES/AR", route: AppRoutes.localizations),
Chapter(name: "Location", route: AppRoutes.location),
Chapter(name: "Browser Demo", route: AppRoutes.browser),
Chapter(name: "GraphQL", route: AppRoutes.graphQL),
Chapter(name: "Gallery", route: AppRoutes.cameraFiles),
Chapter(name: "Firebase - Notification", route: AppRoutes.firebaseNotification),
];
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(
message: StringConstants.appName,
),
body: Container(
child: ListView.builder(
padding: const EdgeInsets.all(4),
itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
Chapter chapter = entries[index];
return ChapterWidget(chapter: chapter);
}),
),
);
}
}
| 0 |
mirrored_repositories/Flare | mirrored_repositories/Flare/lib/main.dart | import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flare/core/localization/app_localization_delegate.dart';
import 'package:flare/core/style/app_theme.dart';
import 'package:flare/routes/app_route_delegates.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:provider/provider.dart';
void main() async {
// We're using HiveStore for persistence,
// so we need to initialize Hive.
await initHiveForFlutter();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(providers: [
ChangeNotifierProvider(create: (_) => AppTheme(themeLight))
], child: MaterialAppWithTheme());
}
}
class MaterialAppWithTheme extends StatelessWidget {
MaterialAppWithTheme({super.key});
final _routerDelegate = RoutesDelegator().routerDelegate;
@override
Widget build(BuildContext context) {
final theme = Provider.of<AppTheme>(context);
return MaterialApp.router(
debugShowCheckedModeBanner: false,
theme: theme.getTheme,
routerDelegate: _routerDelegate,
routeInformationParser: BeamerParser(),
backButtonDispatcher:
BeamerBackButtonDispatcher(delegate: _routerDelegate),
localizationsDelegates: const [
AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: const [
Locale('en', ''),
Locale('es', ''),
Locale('ar', ''),
],
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/browser/browser_screen.dart | import 'package:flare/core/utils/app_constants.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
class BrowserScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return BrowserScreenState();
}
}
class BrowserScreenState extends State<BrowserScreen> {
String url = "https://flutter.dev/learn";
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBarWidget(message: StringConstants.screenBrowserUrlLaunch),
body: Container(
padding: EdgeInsets.all(AppConstants.sixteen),
child: Column(
children: [
ElevatedButton(
onPressed: () => {_launchUrl()}, child: Text("Launch"))
],
),
));
}
Future<void> _launchUrl() async {
if (!await launchUrl(Uri.parse(url),
mode: LaunchMode.externalApplication)) {
throw 'Could not launch $url';
}
}
}
| 0 |
mirrored_repositories/Flare/lib/features/blocstate | mirrored_repositories/Flare/lib/features/blocstate/view/album_list_item.dart | import 'package:flare/core/style/styles.dart';
import 'package:flutter/cupertino.dart';
import 'package:flare/features/blocstate/data/album.dart';
import 'package:flutter/material.dart';
class AlbumListItem extends StatelessWidget {
final Album album;
AlbumListItem(this.album);
@override
Widget build(BuildContext context) {
return Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(8)),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
album.title,
style: Styles.h5Regular,
textAlign: TextAlign.start,
maxLines: 2,
),
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features/blocstate | mirrored_repositories/Flare/lib/features/blocstate/view/album_view.dart | import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:flare/features/blocstate/view/album_list_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flare/core/widgets/loading_widget.dart';
import 'package:flare/core/widgets/message_display.dart';
import 'package:flare/features/blocstate/bloc/album_bloc.dart';
import 'package:flare/features/blocstate/bloc/album_event.dart';
import 'package:flare/features/blocstate/bloc/album_state.dart';
class AlbumScreen extends StatefulWidget {
const AlbumScreen() : super(key: const Key(StringConstants.keyAlbumScreen));
@override
State<StatefulWidget> createState() {
return AlbumScreenState();
}
}
class AlbumScreenState extends State<AlbumScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(message: StringConstants.screenBlocHttpApiCall),
body: buildBody(context),
);
}
BlocProvider<AlbumBloc> buildBody(BuildContext context) {
return BlocProvider(
create: (_) => AlbumBloc(),
child: BlocBuilder<AlbumBloc, AlbumState>(
builder: (context, state) {
if (state is Initial) {
context.read<AlbumBloc>().add(GetAlbum());
return const MessageDisplay(key: Key("Key"), message: "Loading Album");
} else if (state is Empty) {
return const MessageDisplay(key: Key("Key"), message: "No Album Found");
} else if (state is Loading) {
return const LoadingWidget(key: Key(""));
} else if (state is Loaded) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: state.albums.length,
itemBuilder: (context, index) {
return AlbumListItem(state.albums[index]);
});
} else if (state is Error) {
return MessageDisplay(
key: Key(state.message),
message: state.message,
);
} else {
return const MessageDisplay(key: Key("Key"), message: "No Data Found Else");
}
},
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features/blocstate | mirrored_repositories/Flare/lib/features/blocstate/data/album.dart | class Album {
final int userId;
final int id;
final String title;
const Album({
required this.userId,
required this.id,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features/blocstate | mirrored_repositories/Flare/lib/features/blocstate/bloc/album_event.dart | import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
@immutable
abstract class AlbumEvent extends Equatable {
@override
List<Object> get props => [];
}
class GetAlbum extends AlbumEvent {} | 0 |
mirrored_repositories/Flare/lib/features/blocstate | mirrored_repositories/Flare/lib/features/blocstate/bloc/album_bloc.dart | import 'dart:convert';
import 'package:flare/core/utils/logger.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/features/blocstate/bloc/album_event.dart';
import 'package:flare/features/blocstate/bloc/album_state.dart';
import 'package:flare/features/blocstate/data/album.dart';
import 'package:http/http.dart' as http;
import 'package:bloc/bloc.dart';
class AlbumBloc extends Bloc<AlbumEvent, AlbumState> {
AlbumBloc() : super(Initial()) {
on<AlbumEvent>((event, emit) async {
emit(Loading());
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/'));
final strResponse = response.body.toString();
Logger.d("Response: " + strResponse);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
Iterable l = json.decode(response.body);
List<Album> albums = List<Album>.from(l.map((model)=> Album.fromJson(model)));
emit(Loaded(albums: albums));
} else {
// If the server did not return a 200 OK response,
// then set empty.
emit(Error(message: StringConstants.unknownError));
}
});
}
}
| 0 |
mirrored_repositories/Flare/lib/features/blocstate | mirrored_repositories/Flare/lib/features/blocstate/bloc/album_state.dart | import 'package:equatable/equatable.dart';
import 'package:flare/features/blocstate/data/album.dart';
import 'package:meta/meta.dart';
@immutable
abstract class AlbumState extends Equatable {
@override
List<Object> get props => [];
}
class Initial extends AlbumState {}
class Empty extends AlbumState {}
class Loading extends AlbumState {}
class Loaded extends AlbumState {
final List<Album> albums;
Loaded({required this.albums});
@override
List<Object> get props => [albums];
}
class Error extends AlbumState {
final String message;
Error({required this.message});
@override
List<Object> get props => [message];
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/localizations/localization_screen.dart | import 'package:flare/core/utils/app_constants.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flare/core/localization/app_localization.dart';
class CustomLocalizationScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return CustomLocalizationScreenState();
}
}
class CustomLocalizationScreenState extends State<CustomLocalizationScreen> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(
message: StringConstants.screenLocalization,
),
body: Container(
padding: EdgeInsets.all(AppConstants.sixteen),
child: Column(
children: [Text(AppLocalization.of(context).title)],
),
));
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/uicomponent/card_and_chip_screen.dart | import 'package:flare/core/models/OptionItem.dart';
import 'package:flutter/material.dart';
import 'package:flare/core/style/color_constants.dart';
import 'package:flare/core/style/styles.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
class CardAndChipScreen extends StatefulWidget {
CardAndChipScreen() : super(key: Key(""));
@override
_CardAndChipScreenState createState() => _CardAndChipScreenState();
}
class _CardAndChipScreenState extends State<CardAndChipScreen> {
bool isFavorite = false;
int inputChipSingle = 3;
int? selectedIndexInputChipSingle;
List<OptionItem> optionList = [
OptionItem(1, "Option 1", false),
OptionItem(2, "Option 2", false),
OptionItem(3, "Option 3", false),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:
AppBarWidget(message: StringConstants.screenUiComponentCardAndChips),
body: SingleChildScrollView(
padding: EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text("Card - Simple Text", style: Styles.h5Regular),
const Card(
color: ColorConstants.gray20,
child: Padding(
padding: EdgeInsets.all(8),
child: Text(
"Simple Text Card",
style: TextStyle(color: ColorConstants.white),
),
)),
const SizedBox(height: 20),
const Text("Card - Outlined", style: Styles.h5Regular),
Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(12)),
),
child: const ListTile(
leading: Icon(Icons.map_outlined),
title: Text("Flutter", style: Styles.h4SemiBold),
subtitle: Text(StringConstants.dummyFlutterShort,
style: Styles.h5Regular),
),
),
const SizedBox(height: 20),
const Text("Card - List Tile Action Buttons", style: Styles.h5Regular),
Card(
child: Column(
children: [
const ListTile(
leading: Icon(Icons.map_outlined),
title: Text("Flutter", style: Styles.h4SemiBold),
subtitle: Text(StringConstants.dummyFlutter,
style: Styles.h5Regular),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
child: const Text('Button 1'),
onPressed: () {
Fluttertoast.showToast(msg: "Button 1");
},
),
const SizedBox(width: 8),
TextButton(
child: const Text('Button 2'),
onPressed: () {
Fluttertoast.showToast(msg: "Button 2");
},
),
const SizedBox(width: 8),
],
)
],
)),
const SizedBox(height: 20),
const Text("Card - Network Image", style: Styles.h5Regular),
Card(
semanticContainer: true,
clipBehavior: Clip.antiAliasWithSaveLayer,
child: Image.network(
"https://placeimg.com/640/150/any",
fit: BoxFit.cover,
height: 150,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) {
return child;
}
return Container(
height: 150,
child: Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
),
);
},
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
elevation: 5,
),
const SizedBox(height: 20),
const Text("Chip", style: Styles.h5Regular),
Chip(
labelPadding: EdgeInsets.all(2.0),
avatar: CircleAvatar(
backgroundColor: Colors.white70,
child: Text("F".toUpperCase()),
),
label: Text("Flutter", style: Styles.h5Regular),
backgroundColor: ColorConstants.gray10,
elevation: 2.0,
shadowColor: Colors.grey[60],
padding: EdgeInsets.all(8.0),
),
const SizedBox(height: 20),
const Text("Action Chip", style: Styles.h5Regular),
ActionChip(
avatar: Icon(isFavorite ? Icons.favorite : Icons.favorite_border),
label: const Text('Save to favorites'),
onPressed: () {
setState(() {
isFavorite = !isFavorite;
});
},
),
const SizedBox(height: 20),
const Text("Input Chips - Single Selection With Delete", style: Styles.h5Regular),
Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(12)),
),
child: Container(
child: Column(
children: <Widget>[
Wrap(
alignment: WrapAlignment.center,
spacing: 5.0,
children: List<Widget>.generate(
inputChipSingle,
(int index) {
return InputChip(
label: Text('Option ${index + 1}'),
selected: selectedIndexInputChipSingle == index,
onSelected: (bool selected) {
setState(() {
if (selectedIndexInputChipSingle == index) {
selectedIndexInputChipSingle = null;
} else {
selectedIndexInputChipSingle = index;
}
});
},
onDeleted: () {
setState(() {
inputChipSingle = inputChipSingle - 1;
});
},
);
},
).toList(),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
setState(() {
inputChipSingle = 3;
});
},
child: const Text('Reset'),
),
SizedBox(width: 16),
ElevatedButton(
onPressed: () {
if(selectedIndexInputChipSingle != null) {
var str = (selectedIndexInputChipSingle!! + 1).toString();
Fluttertoast.showToast(
msg: "Selected option : " + str);
} else {
Fluttertoast.showToast(
msg: "Selected option : Not selected");
}
},
child: const Text('Save'),
)
],
)
],
),
),
),
const SizedBox(height: 20),
const Text("Filter Chips - Multiple Selection", style: Styles.h5Regular),
Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(12)),
),
child: Container(
child: Column(
children: <Widget>[
Wrap(
alignment: WrapAlignment.center,
spacing: 5.0,
children: List<Widget>.generate(
optionList.length,
(int index) {
return FilterChip(
avatar: CircleAvatar(
backgroundColor: ColorConstants.primary,
child: Text(optionList[index].name[0].toUpperCase()),
),
label: Text(optionList[index].name),
selected: optionList[index].isSelected,
selectedColor: Colors.cyanAccent,
onSelected: (bool selected) {
setState(() {
optionList[index].isSelected = !optionList[index].isSelected;
});
},
);
},
).toList(),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
List<String> sList = List.empty(growable: true);
optionList.forEach((element) {
if(element.isSelected){
sList.add(element.name);
}
});
if(sList.isNotEmpty) {
var str = sList.toString();
Fluttertoast.showToast(
msg: "Selected options : " + str);
} else {
Fluttertoast.showToast(msg: "Selected option : Not selected");
}
},
child: const Text('Save'),
)
],
)
],
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/uicomponent/buttons_screen.dart | import 'package:flutter/material.dart';
import 'package:flare/core/style/styles.dart';
import 'package:flare/core/utils/logger.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:flare/features/uicomponent/widgets/checkbox_button_widget.dart';
import 'package:flare/features/uicomponent/widgets/radio_button_widget.dart';
import 'package:flare/features/uicomponent/widgets/switch_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
class ButtonsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(
message: StringConstants.screenUiComponentButton,
),
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text("UI Component - Button", style: Styles.h5Regular),
TextButton(
onPressed: () {
Fluttertoast.showToast(msg: "TextButton clicked");
},
child: Text("Text Button"),
),
SizedBox(height: 20),
Text("Elevated Button", style: Styles.h5Regular),
ElevatedButton(
onPressed: () {
Fluttertoast.showToast(msg: "ElevatedButton clicked");
},
child: Text("Elevated Button"),
),
SizedBox(height: 20),
Text("Outlined Button ", style: Styles.h5Regular),
OutlinedButton(
onPressed: () {
Fluttertoast.showToast(msg: "OutlinedButton clicked");
},
child: Text("Outlined Button"),
),
SizedBox(height: 20),
Text("Floating Action Button ", style: Styles.h5Regular),
FloatingActionButton(
onPressed: () {
Fluttertoast.showToast(msg: "Clicked");
},
heroTag: "1",
child: Icon(Icons.add_alert),
backgroundColor: Colors.blueAccent,
),
SizedBox(height: 20),
Text("Floating Action Button - Label ", style: Styles.h5Regular),
FloatingActionButton(
onPressed: () {
Fluttertoast.showToast(msg: "Clicked");
},
heroTag: "2",
child: Text("Action")),
SizedBox(height: 20),
Text("Floating Action Button - Extended ", style: Styles.h5Regular),
FloatingActionButton.extended(
onPressed: () {},
label: Row(
children: [Icon(Icons.share), Text("Share")],
),
heroTag: "3",
),
SizedBox(height: 20),
Text("PopUp Menu Button", style: Styles.h5Regular),
PopupMenuButton(
itemBuilder: (BuildContext context) => [
const PopupMenuItem(child: Text("Option 1"), value: "Option 1",),
const PopupMenuItem(child: Text("Option 2"), value: "Option 2"),
const PopupMenuItem(child: Text("Option 3"), value: "Option 3")
],
onSelected: (value) {
Logger.d("Selected : " + value);
Fluttertoast.showToast(msg: "Selected : " + value);
},
),
SizedBox(height: 20),
Text("Switch", style: Styles.h5Regular),
SwitchWidget(),
SizedBox(height: 20),
Text("Radio Buttons", style: Styles.h5Regular),
RadioButtonWidget(),
SizedBox(height: 20),
Text("CheckBox Buttons", style: Styles.h5Regular),
CheckBoxButtonWidget(),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/uicomponent/text_inputfield_screen.dart | import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flare/core/style/color_constants.dart';
import 'package:flare/core/style/styles.dart';
import 'package:flare/core/utils/logger.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:flare/features/uicomponent/widgets/custom_form_field_with_domainname.dart';
import 'package:flare/features/uicomponent/widgets/text_input_field_form_example.dart';
import 'package:flare/features/uicomponent/widgets/text_input_field_password_eye_example.dart';
class TextAndInputFieldScreen extends StatelessWidget {
TextEditingController mycontroller = TextEditingController();
String inputText = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(
message: StringConstants.screenUiComponentText,
),
body: SingleChildScrollView(
child: Column(
children: [
//Texts
Text("UI Component - Text", style: Styles.h3SemiBold),
Text("Normal", style: Styles.h5Regular),
Text("SemiBold", style: Styles.h5SemiBold),
Text("Normal - Italic",
style: Styles.h5Regular.merge(const TextStyle(fontStyle: FontStyle.italic))),
Text("Gredient Text",
style: TextStyle(
fontSize: Styles.fontSizeH2,
foreground: Paint()
..shader = ui.Gradient.linear(
Offset(0, 20),
Offset(150, 20),
<Color>[
Colors.red,
Colors.yellow,
],
))),
RichText(
text: TextSpan(
text: 'Hello ',
style: Styles.h5Regular.merge(const TextStyle(color: ColorConstants.gray50)),
children: <TextSpan>[
TextSpan(
text: 'bold',
style: Styles.h4SemiBold.merge(TextStyle(color: ColorConstants.gray50))),
TextSpan(
text: ' Text!',
style: Styles.h5Regular.merge(const TextStyle(color: ColorConstants.gray50))),
],
),
),
RichText(
text: TextSpan(
text: "Hello World",
style: Styles.h5Regular.merge(const TextStyle(color: ColorConstants.black)),
children: <TextSpan>[
TextSpan(
text: 'Span Underline Text',
style: TextStyle(
color: Colors.black,
decoration: TextDecoration.underline,
decorationColor: Colors.red,
decorationStyle: TextDecorationStyle.wavy,
),
),
TextSpan(
text: ' End the normal text',
style: Styles.h5Regular.merge(const TextStyle(color: ColorConstants.black))),
])),
//Input fields
SizedBox(height: 20),
Text("UI Component - Input Fields", style: Styles.h3SemiBold),
SizedBox(height: 20),
Padding(
key: Key(""),
padding: EdgeInsets.all(16),
child: Column(
children: [
//Broadcom
CustomFormFieldWithDomainName(),
//Broadcom
SizedBox(height: 20),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'TextField - Outline Border',
labelText: "Label TextField"),
onChanged: (text) {
inputText = text;
},
),
TextFormField(
obscureText: true,
obscuringCharacter: "*",
decoration: const InputDecoration(
labelText: 'Password',
),
validator: (String? value) {
if (value?.trim().isEmpty == true) {
return 'Password is required';
}
return null;
},
),
TextInputFieldEyePasswordExample(),
Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(8)),
),
child: Padding(
padding: EdgeInsets.all(8),
child: Column(
children: [
TextAutoValidateModeExample(),
],
),
)),
],
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/uicomponent/dialog_screen.dart | import 'package:flutter/material.dart';
import 'package:flare/core/style/styles.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
class DialogScreen extends StatefulWidget {
DialogScreen() : super(key: Key(StringConstants.screenUiComponentDialogs));
@override
_DialogScreenState createState() => _DialogScreenState();
}
class _DialogScreenState extends State<DialogScreen> {
DateTime? selectedDate = null;
TimeOfDay? selectedTime = null;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(
message: StringConstants.screenUiComponentDialogs,
),
body: Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text("Alert Dialog", style: Styles.h5Regular),
ElevatedButton(
onPressed: () {
_showAlertDialog();
},
child: Text("Alert Dialog"),
),
SizedBox(height: 20),
Text("Simple Dialog", style: Styles.h5Regular),
ElevatedButton(
onPressed: () {
_showSimpleDialog();
},
child: Text("Simple Dialog"),
),
SizedBox(height: 20),
Text("Bottom Sheet", style: Styles.h5Regular),
ElevatedButton(
onPressed: () {
_showBottomSheetDialog();
},
child: Text("Bottom Sheet Dialog"),
),
SizedBox(height: 20),
Text("Date Picker", style: Styles.h5Regular),
Text(selectedDate == null //ternary expression to check if date is null
? 'No date was chosen!'
: 'Picked Date: ${selectedDate.toString()}'),
ElevatedButton(
onPressed: () {
_showDatePickerDialog();
},
child: Text("DatePicker Dialog"),
),
SizedBox(height: 20),
Text("Time Picker", style: Styles.h5Regular),
Text(selectedTime == null //ternary expression to check if date is null
? 'No time was chosen!'
: 'Picked Time: ${selectedTime.toString()}'),
ElevatedButton(
onPressed: () {
_showTimePickerDialog();
},
child: Text("TimePicker Dialog"),
),
],
),
),
);
}
Future<void> _showBottomSheetDialog() async {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return SizedBox(
child: Wrap(
children: [
ListTile(
leading: Icon(Icons.share),
title: Text("Share"),
onTap: () {
Fluttertoast.showToast(msg: "Share");
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.delete),
title: Text("Delete"),
onTap: () {
Fluttertoast.showToast(msg: "Delete");
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.linked_camera),
title: Text("Camera"),
onTap: () {
Fluttertoast.showToast(msg: "Camera");
Navigator.pop(context);
},
)
],
),
);
});
}
Future<void> _showSimpleDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('SimpleDialog'),
children: [
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, 'Picture');
Fluttertoast.showToast(msg: "Take Picture");
},
child: Text('Take Picture'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, 'Gallery');
Fluttertoast.showToast(msg: "Gallery");
},
child: Text('Select From Gallery'),
)
],
);
},
);
}
Future<void> _showAlertDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: const Text('AlertDialog'),
content: SingleChildScrollView(
child: ListBody(
children: const <Widget>[
Text(StringConstants.dummyFlutter),
],
),
),
actions: <Widget>[
TextButton(
onPressed: () {
Fluttertoast.showToast(msg: "Cancel");
Navigator.pop(context, 'Cancel');
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Fluttertoast.showToast(msg: "OK");
Navigator.pop(context, 'OK');
},
child: const Text('OK'),
),
],
);
},
);
}
Future<void> _showDatePickerDialog() async {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(1950),
lastDate: DateTime(2050),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
selectedDate = pickedDate;
});
});
}
Future<void> _showTimePickerDialog() async {
showTimePicker(context: context, initialTime: TimeOfDay.now()).then((pickedTime) {
if (pickedTime == null) {
return;
}
setState(() {
selectedTime = pickedTime;
});
});
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/uicomponent/app_bar_screen.dart | import 'package:flutter/material.dart';
import 'package:flare/core/style/styles.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
class AppBarScreen extends StatefulWidget {
AppBarScreen() : super(key: Key("AppBar"));
@override
State<AppBarScreen> createState() => _AppBarScreenState();
}
class _AppBarScreenState extends State<AppBarScreen> {
List<Widget> actionList = [
InkWell(
onTap: () {
Fluttertoast.showToast(msg: "Favourite Action button clicked");
},
child: Padding(
padding: EdgeInsets.only(left: 8, right: 8),
child: Icon(Icons.favorite)
),
),
InkWell(
onTap: () {
Fluttertoast.showToast(msg: "Download Action button clicked");
},
child: Padding(
padding: EdgeInsets.only(left: 8, right: 8),
child: Icon(Icons.vertical_align_bottom_sharp)
),
)
];
List<Widget> actionListEmpty = List.empty(growable: true);
bool leadingIcon = false;
bool actionIcons = false;
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue;
}
return Colors.red;
}
@override
Widget build(BuildContext context) {
Widget? leadingWidget = null;
List<Widget>? actionWidgets = null;
if (leadingIcon) {
leadingWidget = InkWell(
onTap: () {
Fluttertoast.showToast(msg: "Leading button clicked");
},
child: Icon(Icons.add_alert),
);
}
if (actionIcons) {
actionWidgets = actionList;
}
return Scaffold(
appBar: AppBarWidget(
message: StringConstants.screenUiComponentAppBar,
leading: leadingWidget,
actionList: actionWidgets,
),
body: Container(
child: Column(
children: [
SizedBox(height: 20),
ListTile(
title: Text("Want to add leading icon"),
leading: Checkbox(
checkColor: Colors.white,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: leadingIcon,
onChanged: (bool? value) {
setState(() {
leadingIcon = value!;
});
},
)),
SizedBox(height: 20),
ListTile(
title: Text("Want to add Action icons"),
leading: Checkbox(
checkColor: Colors.white,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: actionIcons,
onChanged: (bool? value) {
setState(() {
actionIcons = value!;
});
},
)),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/uicomponent/bottom_nav_bar_screen.dart | import 'package:flare/core/style/color_constants.dart';
import 'package:flutter/material.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
class BottomNavBarScreen extends StatefulWidget {
BottomNavBarScreen() : super(key: Key("BottomNavScreen"));
@override
State<BottomNavBarScreen> createState() => _BottomNavBarScreenState();
}
class _BottomNavBarScreenState extends State<BottomNavBarScreen> {
int _selectedIndex = 0;
static final List<Widget> _widgetOptions = <Widget>[
OneScreen(),
TwoScreen(),
ThreeScreen(),
FourScreen(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _selectedIndex,
children: _widgetOptions,
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: "One",
),
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit_sharp),
label: "Two",
),
BottomNavigationBarItem(
icon: Icon(Icons.accessible_forward_outlined),
label: "Three",
),
BottomNavigationBarItem(
icon: Icon(Icons.add_business_rounded),
label: "Four",
),
],
currentIndex: _selectedIndex,
showUnselectedLabels: true,
onTap: _onItemTapped,
type: BottomNavigationBarType.fixed,
selectedItemColor: ColorConstants.primary,
unselectedItemColor: ColorConstants.primaryAssent,
),
);
}
}
class OneScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(
message: "One",
),
backgroundColor: Colors.lightGreen,
body: Container(
child: Center(
child: Text("One"),
),
),
);
}
}
class TwoScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(
message: "Two",
),
backgroundColor: Colors.orange,
body: Container(
child: Center(
child: Text("Two"),
),
),
);
}
}
class ThreeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(
message: "Three",
),
backgroundColor: Colors.red,
body: Container(
child: Center(
child: Text("Three"),
),
),
);
}
}
class FourScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(
message: "Four",
),
backgroundColor: Colors.yellow,
body: Container(
child: Center(
child: Text("Four"),
),
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/uicomponent/tabbar_screen.dart | import 'package:flutter/material.dart';
import 'package:flare/core/utils/string_constants.dart';
class TabbarScreen extends StatefulWidget {
TabbarScreen() : super(key: Key(StringConstants.screenUiComponentTabBar));
@override
_TabbarScreenState createState() => _TabbarScreenState();
}
class _TabbarScreenState extends State<TabbarScreen> with TickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
// TODO: implement initState
super.initState();
_tabController = TabController(length: 3, vsync: this);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(StringConstants.screenUiComponentTabBar),
bottom: TabBar(
controller: _tabController,
indicatorColor: Colors.white,
tabs: [
Tab(
icon: Icon(Icons.home),
),
Tab(
icon: Icon(Icons.search),
),
Tab(
icon: Icon(Icons.card_travel),
)
],
),
),
body: TabBarView(
controller: _tabController,
children: [
Center(
child: Text("Home Screen"),
),
Center(
child: Text("Search Screen"),
),
Center(
child: Text("Cart Screen"),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/uicomponent/drawer_screen.dart | import 'package:flutter/material.dart';
import 'package:flare/core/style/color_constants.dart';
import 'package:flare/core/style/styles.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
class DrawerScreen extends StatefulWidget {
DrawerScreen() : super(key: Key("Drawer"));
@override
_DrawerScreenState createState() => _DrawerScreenState();
}
class _DrawerScreenState extends State<DrawerScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(message: StringConstants.screenUiComponentDrawer),
drawer: Drawer(
child: ListView(
children: [
DrawerHeader(
decoration: BoxDecoration(color: ColorConstants.primary),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FadeInImage.assetNetwork(
placeholder: 'assets/img/image_loader.gif',
image: 'https://picsum.photos/250?image=9',
width: 50,
height: 50,
),
Text("Header", style: Styles.h4SemiBold),
Text(
"[email protected]",
style: Styles.h5Regular,
)
],
)),
ListTile(
leading: Icon(Icons.home),
title: Text("Home"),
onTap: () {
Navigator.pop(context);
Fluttertoast.showToast(msg: "Home");
},
),
ListTile(
leading: Icon(Icons.settings),
title: Text("Settings"),
onTap: () {
Navigator.pop(context);
Fluttertoast.showToast(msg: "Settings");
},
),
ListTile(
leading: Icon(Icons.share),
title: Text("Share"),
onTap: () {
Navigator.pop(context);
Fluttertoast.showToast(msg: "Share");
},
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features/uicomponent | mirrored_repositories/Flare/lib/features/uicomponent/widgets/checkbox_button_widget.dart | import 'package:flutter/material.dart';
import 'package:flare/core/utils/logger.dart';
import 'package:fluttertoast/fluttertoast.dart';
class CheckBoxButtonWidget extends StatefulWidget {
@override
_CheckBoxButtonWidgetState createState() => _CheckBoxButtonWidgetState();
}
class _CheckBoxButtonWidgetState extends State<CheckBoxButtonWidget> {
List<MobileOS> osList = [
MobileOS(isChecked: false, name: "Android"),
MobileOS(isChecked: false, name: "iOS"),
MobileOS(isChecked: false, name: "Windows"),
];
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue;
}
return Colors.red;
}
@override
Widget build(BuildContext context) {
return Container(
child: Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(8)),
),
child: Padding(
padding: EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ListTile(
title: Text(osList[0].name),
leading: Checkbox(
checkColor: Colors.white,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: osList[0].isChecked,
onChanged: (bool? value) {
setState(() {
osList[0].isChecked = value!;
});
},
)),
ListTile(
title: Text(osList[1].name),
leading: Checkbox(
checkColor: Colors.white,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: osList[1].isChecked,
onChanged: (bool? value) {
setState(() {
osList[1].isChecked = value!;
});
},
)),
ListTile(
title: Text(osList[2].name),
leading: Checkbox(
checkColor: Colors.white,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: osList[2].isChecked,
onChanged: (bool? value) {
setState(() {
osList[2].isChecked = value!;
});
},
)),
ElevatedButton(
onPressed: () {
String selected = "Selected OS : \n";
if (osList != null) {
osList.forEach((element) {
if(element.isChecked){
selected = selected + "\n" + " Name: " + element.name + " , iSChecked : "+ element.isChecked.toString();
}
});
Fluttertoast.showToast(msg: selected);
}
},
child: Text("Save"))
],
),
)),
);
}
}
class MobileOS {
bool isChecked;
String name;
MobileOS({required this.isChecked, required this.name});
}
| 0 |
mirrored_repositories/Flare/lib/features/uicomponent | mirrored_repositories/Flare/lib/features/uicomponent/widgets/custom_form_field_with_domainname.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flare/core/style/styles.dart';
class CustomFormFieldWithDomainName extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: 50,
decoration: BoxDecoration(
border: Border.all(width: 1, color: Colors.grey),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Expanded(
flex: 55,
child: Container(
padding: const EdgeInsets.only(left: 16, top: 0, right: 8, bottom: 0),
width: double.infinity,
child: TextFormField(
decoration: const InputDecoration(
hintText: "Enter your email ID",
border: InputBorder.none,
),
keyboardType: TextInputType.multiline,
maxLines: 2,
style: Styles.h5Regular,
textAlign: TextAlign.start,
textAlignVertical: TextAlignVertical.center,
),
),
),
Expanded(
flex: 5,
child: Container(
padding: const EdgeInsets.all(4),
child: Text("|", style: Styles.h2Regular.merge(TextStyle(color: Colors.grey))),
),
),
Expanded(
flex: 40,
child: Container(
padding: const EdgeInsets.all(4),
child: Text("@domain.net", style: Styles.h5Regular),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features/uicomponent | mirrored_repositories/Flare/lib/features/uicomponent/widgets/radio_button_widget.dart | import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class RadioButtonWidget extends StatefulWidget {
@override
_RadioButtonWidgetState createState() => _RadioButtonWidgetState();
}
class _RadioButtonWidgetState extends State<RadioButtonWidget> {
MobileOS? _os;
@override
Widget build(BuildContext context) {
return Container(
child: Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(8)),
),
child: Padding(
padding: EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ListTile(
title: const Text('Android'),
leading: Radio<MobileOS>(
value: MobileOS.Android,
groupValue: _os,
onChanged: (MobileOS? value) {
setState(() {
_os = value;
});
},
)
),
ListTile(
title: const Text('iOS'),
leading: Radio<MobileOS>(
value: MobileOS.iOS,
groupValue: _os,
onChanged: (MobileOS? value) {
setState(() {
_os = value;
});
},
)
),
ListTile(
title: const Text('Windows'),
leading: Radio<MobileOS>(
value: MobileOS.Windows,
groupValue: _os,
onChanged: (MobileOS? value) {
setState(() {
_os = value;
});
},
)
),
ElevatedButton(onPressed: (){
if(_os != null) {
Fluttertoast.showToast(msg: "Selected OS : " + _os!.name.toString());
}
}, child: Text("Save"))
],
),
)),
);
}
}
enum MobileOS { Android, iOS, Windows }
| 0 |
mirrored_repositories/Flare/lib/features/uicomponent | mirrored_repositories/Flare/lib/features/uicomponent/widgets/text_input_field_form_example.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class TextAutoValidateModeExample extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _TextAutoValidateModeExampleState();
}
}
class _TextAutoValidateModeExampleState extends State<TextAutoValidateModeExample> {
final _text = TextEditingController();
bool _validate = false;
@override
void dispose() {
_text.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Text('Error Showed if Field is Empty on Submit button Pressed'),
TextField(
controller: _text,
decoration: InputDecoration(
labelText: 'Enter the Value',
errorText: _validate ? 'Value Can\'t Be Empty' : null,
),
onChanged: (text) {
setState(() {
_text.text.isEmpty ? _validate = true : _validate = false;
});
},
),
ElevatedButton(
onPressed: () {
setState(() {
_text.text.isEmpty ? _validate = true : _validate = false;
});
Fluttertoast.showToast(msg: "Value :" + _text.text.toString());
},
child: Text('Submit'),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features/uicomponent | mirrored_repositories/Flare/lib/features/uicomponent/widgets/switch_widget.dart | import 'package:flutter/material.dart';
class SwitchWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _SwitchState();
}
}
class _SwitchState extends State<SwitchWidget> {
bool isToggled = false;
final MaterialStateProperty<Color?> trackColor =
MaterialStateProperty.resolveWith<Color?>(
(Set<MaterialState> states) {
// Track color when the switch is selected.
if (states.contains(MaterialState.selected)) {
return Colors.amber;
}
// Otherwise return null to set default track color
// for remaining states such as when the switch is
// hovered, focused, or disabled.
return null;
},
);
final MaterialStateProperty<Color?> overlayColor =
MaterialStateProperty.resolveWith<Color?>(
(Set<MaterialState> states) {
// Material color when switch is selected.
if (states.contains(MaterialState.selected)) {
return Colors.amber.withOpacity(0.54);
}
// Material color when switch is disabled.
if (states.contains(MaterialState.disabled)) {
return Colors.grey.shade400;
}
// Otherwise return null to set default material color
// for remaining states such as when the switch is
// hovered, or focused.
return null;
},
);
@override
Widget build(BuildContext context) {
return Container(
child: Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(8)),
),
child: Padding(
padding: EdgeInsets.all(8),
child: Row(
children: [
Switch(
value: isToggled,
onChanged: (value) {
setState(() {
isToggled = value;
});
}),
Switch(
value: isToggled,
trackColor: trackColor,
overlayColor: overlayColor,
thumbColor: MaterialStateProperty.all<Color>(Colors.black),
onChanged: (value) {
setState(() {
isToggled = value;
});
}),
],
),
)),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features/uicomponent | mirrored_repositories/Flare/lib/features/uicomponent/widgets/text_input_field_password_eye_example.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class TextInputFieldEyePasswordExample extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return TextInputFieldEyePasswordExampleState();
}
}
class TextInputFieldEyePasswordExampleState extends State<TextInputFieldEyePasswordExample> {
bool _passwordVisible = true;
final _text = TextEditingController();
@override
void initState() {
_passwordVisible = false;
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Text('Text Input Field with eye button'),
TextFormField(
keyboardType: TextInputType.text,
controller: _text,
obscureText: !_passwordVisible, //This will obscure text dynamically
decoration: InputDecoration(
labelText: 'Password',
hintText: 'Enter your password',
// Here is key idea
suffixIcon: IconButton(
icon: Icon(
// Based on passwordVisible state choose the icon
_passwordVisible ? Icons.visibility : Icons.visibility_off,
color: Theme.of(context).primaryColorDark,
),
onPressed: () {
// Update the state i.e. toogle the state of passwordVisible variable
setState(() {
_passwordVisible = !_passwordVisible;
});
},
),
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/camerafiles/gallery_screen.dart | import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flare/core/utils/logger.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:flare/features/camerafiles/take_picture_screen.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class GalleryScreen extends StatefulWidget {
String imagePath = "";
GalleryScreen({required this.imagePath})
: super(key: const Key(StringConstants.keyGalleryScreen));
@override
GalleryScreenState createState() => GalleryScreenState();
}
class GalleryScreenState extends State<GalleryScreen> {
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
Logger.d("Gallery screen : ${widget.imagePath}");
return Scaffold(
appBar: AppBarWidget(message: StringConstants.screenGallery),
body: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
AspectRatio(
aspectRatio: 1,
child: (widget.imagePath.isNotEmpty == true)
? Image.file(File(widget.imagePath))
: Image.asset("assets/img/ic_placeholder.png"),
),
ElevatedButton(
onPressed: () async {
WidgetsFlutterBinding.ensureInitialized();
final cameras = await availableCameras();
final firstCamera = cameras.first;
_navigateToTakePicture(firstCamera);
},
child: const Text("Take Picture"),
),
ElevatedButton(
onPressed: () async {
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(source: ImageSource.gallery);
if (image != null) {
setState(() {
widget.imagePath = image.path;
});
}
},
child: const Text("Select Picture"),
),
],
),
),
),
);
}
Future<void> _navigateToTakePicture(CameraDescription camera) async {
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => TakePictureScreen(camera: camera)),
);
if (!mounted) return;
widget.imagePath = result;
setState(() {});
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/camerafiles/take_picture_screen.dart | import 'dart:io';
import 'package:beamer/beamer.dart';
import 'package:camera/camera.dart';
import 'package:flare/core/utils/logger.dart';
import 'package:flare/routes/app_route_names.dart';
import 'package:flutter/material.dart';
// A screen that allows users to take a picture using a given camera.
class TakePictureScreen extends StatefulWidget {
const TakePictureScreen({
super.key,
required this.camera,
});
final CameraDescription camera;
@override
TakePictureScreenState createState() => TakePictureScreenState();
}
class TakePictureScreenState extends State<TakePictureScreen> {
late CameraController _controller;
late Future<void> _initializeControllerFuture;
@override
void initState() {
super.initState();
// To display the current output from the Camera,
// create a CameraController.
_controller = CameraController(
// Get a specific camera from the list of available cameras.
widget.camera,
// Define the resolution to use.
ResolutionPreset.medium,
);
// Next, initialize the controller. This returns a Future.
_initializeControllerFuture = _controller.initialize();
}
@override
void dispose() {
// Dispose of the controller when the widget is disposed.
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Take a picture')),
// You must wait until the controller is initialized before displaying the
// camera preview. Use a FutureBuilder to display a loading spinner until the
// controller has finished initializing.
body: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the Future is complete, display the preview.
return CameraPreview(_controller);
} else {
// Otherwise, display a loading indicator.
return const Center(child: CircularProgressIndicator());
}
},
),
floatingActionButton: FloatingActionButton(
// Provide an onPressed callback.
onPressed: () async {
// Take the Picture in a try / catch block. If anything goes wrong,
// catch the error.
try {
// Ensure that the camera is initialized.
await _initializeControllerFuture;
// Attempt to take a picture and get the file `image`
// where it was saved.
final image = await _controller.takePicture();
if (!mounted) return;
// If the picture was taken, display it on a new screen.
String path = image.path;
Logger.d("Gallery Picture taken path : $path");
Navigator.pop(context, path);
//Beamer.of(context).beamToNamed(AppRoutes.cameraFiles, data: path);
/*await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => DisplayPictureScreen(
// Pass the automatically generated path to
// the DisplayPictureScreen widget.
imagePath: image.path,
),
),
);*/
} catch (e) {
// If an error occurs, log the error to the console.
print(e);
}
},
child: const Icon(Icons.camera_alt),
),
);
}
}
// A widget that displays the picture taken by the user.
class DisplayPictureScreen extends StatelessWidget {
final String imagePath;
const DisplayPictureScreen({super.key, required this.imagePath});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Display the Picture')),
// The image is stored as a file on the device. Use the `Image.file`
// constructor with the given path to display the image.
body: Image.file(File(imagePath)),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/graphql/graphql_screen.dart | import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
class GraphQLScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return GraphQLState();
}
}
class GraphQLState extends State<GraphQLScreen> {
@override
Widget build(BuildContext context) {
final HttpLink httpLink = HttpLink("https://countries.trevorblades.com/");
final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(
GraphQLClient(
link: httpLink as Link,
cache: GraphQLCache(
store: HiveStore(),
partialDataPolicy: PartialDataCachePolicy.acceptForOptimisticData),
),
);
return GraphQLProvider(
child: GraphQLWidget(),
client: client,
);
}
}
class GraphQLWidget extends StatelessWidget {
final String query = r"""
query GetContinent($code : ID!){
continent(code:$code){
name
countries{
name
code
}
}
}
""";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarWidget(message: StringConstants.screenGraphQL),
body: Query(
options: QueryOptions(
document: gql(query),
variables: const <String, dynamic>{"code": "AF"},
),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
print("Query >> ");
if (result.hasException) {
print(result.exception.toString());
return Center(child: Text(result.exception.toString()));
}
if (result.isLoading) {
print("Loading >> ");
return Center(child: CircularProgressIndicator());
}
if (result.data == null) {
return Center(child: Text("No Data Found !"));
}
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Card(
child: ListTile(
title: Text(
result.data!['continent']['countries'][index]['name']),
subtitle: Text(
result.data!['continent']['countries'][index]["code"]),
),
);
},
itemCount: result.data!['continent']['countries'].length,
);
},
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/locations/location_screen.dart | import 'package:flare/core/style/styles.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/core/widgets/appbar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io' show Platform;
import 'package:geolocator/geolocator.dart';
class LocationScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return LocationScreenState();
}
}
class LocationScreenState extends State<LocationScreen> {
static const String _kLocationServicesDisabledMessage = 'Location services are disabled.';
static const String _kPermissionDeniedMessage = 'Permission denied.';
static const String _kPermissionDeniedForeverMessage = 'Permission denied forever.';
static const String _kPermissionGrantedMessage = 'Permission granted.';
final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
final List<_PositionItem> _positionItems = <_PositionItem>[];
StreamSubscription<Position>? _positionStreamSubscription;
StreamSubscription<ServiceStatus>? _serviceStatusStreamSubscription;
bool positionStreamStarted = false;
@override
void initState() {
super.initState();
_toggleServiceStatusStream();
}
PopupMenuButton _createActions() {
return PopupMenuButton(
elevation: 40,
onSelected: (value) async {
switch (value) {
case 1:
_getLocationAccuracy();
break;
case 2:
_requestTemporaryFullAccuracy();
break;
case 3:
_openAppSettings();
break;
case 4:
_openLocationSettings();
break;
case 5:
setState(_positionItems.clear);
break;
default:
break;
}
},
itemBuilder: (context) => [
if (Platform.isIOS)
const PopupMenuItem(
child: Text("Get Location Accuracy"),
value: 1,
),
if (Platform.isIOS)
const PopupMenuItem(
child: Text("Request Temporary Full Accuracy"),
value: 2,
),
const PopupMenuItem(
child: Text("Open App Settings"),
value: 3,
),
if (Platform.isAndroid || Platform.isWindows)
const PopupMenuItem(
child: Text("Open Location Settings"),
value: 4,
),
const PopupMenuItem(
child: Text("Clear"),
value: 5,
),
],
);
}
@override
Widget build(BuildContext context) {
const sizedBox = SizedBox(
height: 10,
);
return Scaffold(
appBar: AppBarWidget(
message: StringConstants.screenLocation,
actionList: [
_createActions()
],
),
body: ListView.builder(
itemCount: _positionItems.length,
itemBuilder: (context, index) {
final positionItem = _positionItems[index];
if (positionItem.type == _PositionItemType.log) {
return ListTile(
title: Text(positionItem.displayValue,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
)),
);
} else {
return Card(
child: ListTile(
tileColor: Colors.grey,
title: Text(
positionItem.displayValue,
style: const TextStyle(color: Colors.white, fontSize: Styles.fontSizeH6),
),
),
);
}
},
),
floatingActionButton: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
child: (_positionStreamSubscription == null || _positionStreamSubscription!.isPaused)
? const Icon(Icons.play_arrow)
: const Icon(Icons.pause),
onPressed: () {
positionStreamStarted = !positionStreamStarted;
_toggleListening();
},
tooltip: (_positionStreamSubscription == null)
? 'Start position updates'
: _positionStreamSubscription!.isPaused
? 'Resume'
: 'Pause',
backgroundColor: _determineButtonColor(),
),
sizedBox,
FloatingActionButton(
child: const Icon(Icons.my_location),
onPressed: _getCurrentPosition,
),
sizedBox,
FloatingActionButton(
child: const Icon(Icons.bookmark),
onPressed: _getLastKnownPosition,
),
],
),
);
}
Future<void> _getCurrentPosition() async {
final hasPermission = await _handlePermission();
if (!hasPermission) {
return;
}
final position = await _geolocatorPlatform.getCurrentPosition();
_updatePositionList(
_PositionItemType.position,
position.toString(),
);
}
Future<bool> _handlePermission() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await _geolocatorPlatform.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
_updatePositionList(
_PositionItemType.log,
_kLocationServicesDisabledMessage,
);
return false;
}
permission = await _geolocatorPlatform.checkPermission();
if (permission == LocationPermission.denied) {
permission = await _geolocatorPlatform.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
_updatePositionList(
_PositionItemType.log,
_kPermissionDeniedMessage,
);
return false;
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
_updatePositionList(
_PositionItemType.log,
_kPermissionDeniedForeverMessage,
);
return false;
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
_updatePositionList(
_PositionItemType.log,
_kPermissionGrantedMessage,
);
return true;
}
void _updatePositionList(_PositionItemType type, String displayValue) {
_positionItems.add(_PositionItem(type, displayValue));
setState(() {});
}
bool _isListening() =>
!(_positionStreamSubscription == null || _positionStreamSubscription!.isPaused);
Color _determineButtonColor() {
return _isListening() ? Colors.green : Colors.red;
}
void _toggleServiceStatusStream() {
if (_serviceStatusStreamSubscription == null) {
final serviceStatusStream = _geolocatorPlatform.getServiceStatusStream();
_serviceStatusStreamSubscription = serviceStatusStream.handleError((error) {
_serviceStatusStreamSubscription?.cancel();
_serviceStatusStreamSubscription = null;
}).listen((serviceStatus) {
String serviceStatusValue;
if (serviceStatus == ServiceStatus.enabled) {
if (positionStreamStarted) {
_toggleListening();
}
serviceStatusValue = 'enabled';
} else {
if (_positionStreamSubscription != null) {
setState(() {
_positionStreamSubscription?.cancel();
_positionStreamSubscription = null;
_updatePositionList(_PositionItemType.log, 'Position Stream has been canceled');
});
}
serviceStatusValue = 'disabled';
}
_updatePositionList(
_PositionItemType.log,
'Location service has been $serviceStatusValue',
);
});
}
}
void _toggleListening() {
if (_positionStreamSubscription == null) {
final LocationSettings locationSettings = LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 1,
);
final positionStream =
_geolocatorPlatform.getPositionStream(locationSettings: locationSettings);
_positionStreamSubscription = positionStream.handleError((error) {
_positionStreamSubscription?.cancel();
_positionStreamSubscription = null;
}).listen((position) => _updatePositionList(
_PositionItemType.position,
position.toString(),
));
_positionStreamSubscription?.pause();
}
setState(() {
if (_positionStreamSubscription == null) {
return;
}
String statusDisplayValue;
if (_positionStreamSubscription!.isPaused) {
_positionStreamSubscription!.resume();
statusDisplayValue = 'resumed';
} else {
_positionStreamSubscription!.pause();
statusDisplayValue = 'paused';
}
_updatePositionList(
_PositionItemType.log,
'Listening for position updates $statusDisplayValue',
);
});
}
@override
void dispose() {
if (_positionStreamSubscription != null) {
_positionStreamSubscription!.cancel();
_positionStreamSubscription = null;
}
super.dispose();
}
void _getLastKnownPosition() async {
final position = await _geolocatorPlatform.getLastKnownPosition();
if (position != null) {
_updatePositionList(
_PositionItemType.position,
position.toString(),
);
} else {
_updatePositionList(
_PositionItemType.log,
'No last known position available',
);
}
}
void _getLocationAccuracy() async {
final status = await _geolocatorPlatform.getLocationAccuracy();
_handleLocationAccuracyStatus(status);
}
void _requestTemporaryFullAccuracy() async {
final status = await _geolocatorPlatform.requestTemporaryFullAccuracy(
purposeKey: "TemporaryPreciseAccuracy",
);
_handleLocationAccuracyStatus(status);
}
void _handleLocationAccuracyStatus(LocationAccuracyStatus status) {
String locationAccuracyStatusValue;
if (status == LocationAccuracyStatus.precise) {
locationAccuracyStatusValue = 'Precise';
} else if (status == LocationAccuracyStatus.reduced) {
locationAccuracyStatusValue = 'Reduced';
} else {
locationAccuracyStatusValue = 'Unknown';
}
_updatePositionList(
_PositionItemType.log,
'$locationAccuracyStatusValue location accuracy granted.',
);
}
void _openAppSettings() async {
final opened = await _geolocatorPlatform.openAppSettings();
String displayValue;
if (opened) {
displayValue = 'Opened Application Settings.';
} else {
displayValue = 'Error opening Application Settings.';
}
_updatePositionList(
_PositionItemType.log,
displayValue,
);
}
void _openLocationSettings() async {
final opened = await _geolocatorPlatform.openLocationSettings();
String displayValue;
if (opened) {
displayValue = 'Opened Location Settings';
} else {
displayValue = 'Error opening Location Settings';
}
_updatePositionList(
_PositionItemType.log,
displayValue,
);
}
}
enum _PositionItemType {
log,
position,
}
class _PositionItem {
_PositionItem(this.type, this.displayValue);
final _PositionItemType type;
final String displayValue;
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/firebase/firebase_notification_screen.dart | import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flare/core/utils/string_constants.dart';
import 'package:flare/features/firebase/firebase_options.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:http/http.dart' as http;
import 'package:firebase_core/firebase_core.dart';
class FirebaseNotificationScreen extends StatefulWidget {
const FirebaseNotificationScreen()
: super(key: const Key(StringConstants.screenFirebaseNotification));
@override
_FirebaseNotificationScreenState createState() => _FirebaseNotificationScreenState();
}
class _FirebaseNotificationScreenState extends State<FirebaseNotificationScreen> {
int id = 0;
bool _notificationsEnabled = false;
@override
void initState() {
super.initState();
mainFunction();
_requestPermissions();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(StringConstants.screenFirebaseNotification),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () async {
_showNotification();
},
child: const Text("Notification plain title & body")),
ElevatedButton(
onPressed: () async {
_showBigPictureNotificationURL();
},
child: const Text("Notification big picture"))
],
),
),
);
}
Future<void> _requestPermissions() async {
if (Platform.isIOS || Platform.isMacOS) {
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<MacOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
} else if (Platform.isAndroid) {
final AndroidFlutterLocalNotificationsPlugin? androidImplementation =
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
final bool? granted = await androidImplementation?.requestPermission();
setState(() {
_notificationsEnabled = granted ?? false;
});
}
}
Future<void> _showNotification() async {
const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(
'your channel id', 'your channel name',
channelDescription: 'your channel description',
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker');
const DarwinNotificationDetails iosNotificationDetails = DarwinNotificationDetails(
categoryIdentifier: darwinNotificationCategoryPlain,
);
const NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails, iOS: iosNotificationDetails);
await flutterLocalNotificationsPlugin
.show(id++, 'plain title', 'plain body', notificationDetails, payload: 'item x');
}
Future<void> _showBigPictureNotificationURL() async {
final ByteArrayAndroidBitmap largeIcon =
ByteArrayAndroidBitmap(await _getByteArrayFromUrl('https://dummyimage.com/48x48'));
final ByteArrayAndroidBitmap bigPicture =
ByteArrayAndroidBitmap(await _getByteArrayFromUrl('https://dummyimage.com/400x800'));
final BigPictureStyleInformation bigPictureStyleInformation = BigPictureStyleInformation(
bigPicture,
largeIcon: largeIcon,
contentTitle: 'overridden <b>big</b> content title',
htmlFormatContentTitle: true,
summaryText: 'summary <i>text</i>',
htmlFormatSummaryText: true);
final AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(
'big text channel id', 'big text channel name',
channelDescription: 'big text channel description',
styleInformation: bigPictureStyleInformation);
final NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
await flutterLocalNotificationsPlugin.show(
id++, 'big text title', 'silent body', notificationDetails);
}
Future<Uint8List> _getByteArrayFromUrl(String url) async {
final http.Response response = await http.get(Uri.parse(url));
return response.bodyBytes;
}
}
String? selectedNotificationPayload;
/// A notification action which triggers a url launch event
const String urlLaunchActionId = 'id_1';
/// A notification action which triggers a App navigation event
const String navigationActionId = 'id_3';
/// Defines a iOS/MacOS notification category for text input actions.
const String darwinNotificationCategoryText = 'textCategory';
/// Defines a iOS/MacOS notification category for plain actions.
const String darwinNotificationCategoryPlain = 'plainCategory';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
/// Streams are created so that app can respond to notification-related events
/// since the plugin is initialised in the `main` function
final StreamController<RemoteMessage> didReceiveLocalNotificationStream =
StreamController<RemoteMessage>.broadcast();
final StreamController<String?> selectNotificationStream = StreamController<String?>.broadcast();
const MethodChannel platform = MethodChannel('dexterx.dev/flutter_local_notifications_example');
const String portName = 'notification_send_port';
/// Note: permissions aren't requested here just to demonstrate that can be
/// done later
final List<DarwinNotificationCategory> darwinNotificationCategories = <DarwinNotificationCategory>[
DarwinNotificationCategory(
darwinNotificationCategoryText,
actions: <DarwinNotificationAction>[
DarwinNotificationAction.text(
'text_1',
'Action 1',
buttonTitle: 'Send',
placeholder: 'Placeholder',
),
],
),
DarwinNotificationCategory(
darwinNotificationCategoryPlain,
actions: <DarwinNotificationAction>[
DarwinNotificationAction.plain('id_1', 'Action 1'),
DarwinNotificationAction.plain(
'id_2',
'Action 2 (destructive)',
options: <DarwinNotificationActionOption>{
DarwinNotificationActionOption.destructive,
},
),
DarwinNotificationAction.plain(
navigationActionId,
'Action 3 (foreground)',
options: <DarwinNotificationActionOption>{
DarwinNotificationActionOption.foreground,
},
),
DarwinNotificationAction.plain(
'id_4',
'Action 4 (auth required)',
options: <DarwinNotificationActionOption>{
DarwinNotificationActionOption.authenticationRequired,
},
),
],
options: <DarwinNotificationCategoryOption>{
DarwinNotificationCategoryOption.hiddenPreviewShowTitle,
},
)
];
@pragma('vm:entry-point')
void notificationTapBackground(NotificationResponse notificationResponse) {
// ignore: avoid_print
print('notification(${notificationResponse.id}) action tapped: '
'${notificationResponse.actionId} with'
' payload: ${notificationResponse.payload}');
if (notificationResponse.input?.isNotEmpty ?? false) {
// ignore: avoid_print
print('notification action tapped with input: ${notificationResponse.input}');
}
}
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await setupFlutterNotifications();
showFlutterNotification(message);
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
print('Handling a background message ${message.messageId}');
}
/// Create a [AndroidNotificationChannel] for heads up notifications
late AndroidNotificationChannel channel;
bool isFlutterLocalNotificationsInitialized = false;
void mainFunction() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
final DarwinInitializationSettings initializationSettingsDarwin = DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
onDidReceiveLocalNotification: (int id, String? title, String? body, String? payload) async {
didReceiveLocalNotificationStream.add(
/*ReceivedNotification(
id: id,
title: title,
body: body,
payload: payload,
),*/
RemoteMessage(
senderId: id.toString(),
data: {
"title": title,
"body" : body,
"payload": payload
}
)
);
},
notificationCategories: darwinNotificationCategories,
);
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsDarwin,
macOS: initializationSettingsDarwin,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) {
switch (notificationResponse.notificationResponseType) {
case NotificationResponseType.selectedNotification:
selectNotificationStream.add(notificationResponse.payload);
break;
case NotificationResponseType.selectedNotificationAction:
if (notificationResponse.actionId == navigationActionId) {
selectNotificationStream.add(notificationResponse.payload);
}
break;
}
},
onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
);
await setupFlutterNotifications();
}
Future<void> setupFlutterNotifications() async {
if (isFlutterLocalNotificationsInitialized) {
return;
}
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.high,
);
/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
if(Platform.isIOS) {
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
FirebaseMessaging.onMessage.listen(showFlutterNotification);
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('A new onMessageOpenedApp event was published!');
showFlutterNotification(message);
});
isFlutterLocalNotificationsInitialized = true;
}
void showFlutterNotification(RemoteMessage message) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
if (notification != null && android != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
// TODO add a proper drawable resource to android, for now using
// one that already exists in example app.
icon: 'launch_background',
),
),
);
}
}
| 0 |
mirrored_repositories/Flare/lib/features | mirrored_repositories/Flare/lib/features/firebase/firebase_options.dart | // Copyright 2022, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'AIzaSyCCSJF_JcTCApO7ad2GBBHJJ3pVernL8R8',
appId: '1:445933177480:android:2901f5434ae4cd7439ed3d',
messagingSenderId: '445933177480',
projectId: 'flutter-notification-1a78d',
databaseURL:
'https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app',
storageBucket: 'flutter-notification-1a78d.appspot.com',
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c',
appId: '1:406099696497:ios:1b423b89c63b82053574d0',
messagingSenderId: '406099696497',
projectId: 'flutter-notification-1a78d',
databaseURL:
'https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app',
storageBucket: 'flutterfire-e2e-tests.appspot.com',
androidClientId:
'406099696497-17qn06u8a0dc717u8ul7s49ampk13lul.apps.googleusercontent.com',
iosClientId:
'406099696497-irb7edfevfkhi6t5s9kbuq1mt1og95rg.apps.googleusercontent.com',
iosBundleId: 'io.flutter.plugins.firebase.messaging',
);
}
| 0 |
mirrored_repositories/Flare/lib | mirrored_repositories/Flare/lib/routes/app_route_delegates.dart | import 'package:beamer/beamer.dart';
import 'package:camera/camera.dart';
import 'package:flare/core/utils/logger.dart';
import 'package:flare/features/camerafiles/gallery_screen.dart';
import 'package:flare/features/camerafiles/take_picture_screen.dart';
import 'package:flare/features/firebase/firebase_notification_screen.dart';
import 'package:flare/features/graphql/graphql_screen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flare/HomeScreen.dart';
import 'package:flare/core/widgets/page_not_found.dart';
import 'package:flare/features/blocstate/view/album_view.dart';
import 'package:flare/features/browser/browser_screen.dart';
import 'package:flare/features/localizations/localization_screen.dart';
import 'package:flare/features/locations/location_screen.dart';
import 'package:flare/features/uicomponent/app_bar_screen.dart';
import 'package:flare/features/uicomponent/bottom_nav_bar_screen.dart';
import 'package:flare/features/uicomponent/buttons_screen.dart';
import 'package:flare/features/uicomponent/card_and_chip_screen.dart';
import 'package:flare/features/uicomponent/dialog_screen.dart';
import 'package:flare/features/uicomponent/drawer_screen.dart';
import 'package:flare/features/uicomponent/tabbar_screen.dart';
import 'package:flare/features/uicomponent/text_inputfield_screen.dart';
import 'package:flare/routes/app_route_names.dart';
///RoutesDelegator classes handle all navigation throughout the app.
class RoutesDelegator {
final routerDelegate = BeamerDelegate(
locationBuilder: RoutesLocationBuilder(
routes: {
"/" : (context, state, data) => HomeScreen(),
AppRoutes.home: (context, state, data) => HomeScreen(),
AppRoutes.uiComponentAppBar: (context, state, data) => AppBarScreen(),
AppRoutes.uiComponentBottomNavigationBar: (context, state, data) => BottomNavBarScreen(),
AppRoutes.uiComponentTextFormField: (context, state, data) => TextAndInputFieldScreen(),
AppRoutes.uiComponentButton: (context, state, data) => ButtonsScreen(),
AppRoutes.uiComponentDrawer: (context, state, data) => DrawerScreen(),
AppRoutes.uiComponentTabBar: (context, state, data) => TabbarScreen(),
AppRoutes.uiComponentDialogs: (context, state, data) => DialogScreen(),
AppRoutes.uiComponentCards: (context, state, data) => CardAndChipScreen(),
AppRoutes.bloc: (context, state, data) => const AlbumScreen(),
AppRoutes.localizations: (context, state, data) => CustomLocalizationScreen(),
AppRoutes.location: (context, state, data) => LocationScreen(),
AppRoutes.browser: (context, state, data) => BrowserScreen(),
AppRoutes.graphQL: (context, state, data) => GraphQLScreen(),
AppRoutes.cameraFiles: (context, state, data) {
String? path = "";
if (data != null && data is String) {
path = data;
}
if (path != null && path.isNotEmpty) {
Logger.d("Gallery beamer file path : $path");
return GalleryScreen(
imagePath: path,
);
} else {
return GalleryScreen(
imagePath: "",
);
}
},
AppRoutes.takePicture: (context, state, data) => TakePictureScreen(
camera: data as CameraDescription,
),
AppRoutes.firebaseNotification: (context, state, data) => FirebaseNotificationScreen(),
},
),
notFoundPage: BeamPage(child: NotFoundPage()));
}
| 0 |
mirrored_repositories/Flare/lib | mirrored_repositories/Flare/lib/routes/app_route_names.dart | ///AppRouteName classes to hold all application screen routes
class AppRoutes {
static const String home = "/home";
static const String uiComponentAppBar = "/appbar";
static const String uiComponentBottomNavigationBar = "/bottomnavbar";
static const String uiComponentTextFormField = "/text";
static const String uiComponentButton = "/button";
static const String uiComponentDrawer = "/drawer";
static const String uiComponentTabBar = "/tabbar";
static const String uiComponentDialogs = "/dialogs";
static const String uiComponentCards = "/cards";
static const String bloc = "/bloc";
static const String localizations = "/localizations";
static const String location = "/location";
static const String browser = "/browser";
static const String graphQL = "/graphql";
static const String cameraFiles = "/home/cameraFiles";
static const String takePicture = "/home/cameraFiles/takePicture";
static const String selectFromGallery = "home/cameraFiles/selectFromGallery";
static const String firebaseNotification = "/home/firebaseNotification";
}
| 0 |
Subsets and Splits