repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/Quizler | mirrored_repositories/Quizler/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'screens/home_screen.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomeScreen(),
);
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/widgets/difficulty_tile.dart | import 'package:flutter/material.dart';
import 'package:trivia_app/screens/loading_screen.dart';
import 'package:trivia_app/utility/card_details.dart';
class DifficultyTile extends StatelessWidget {
DifficultyTile({
Key? key,
required this.selectedIndex,
required this.difficulty,
}) : super(key: key);
final int selectedIndex;
final int difficulty;
final List<String> level = ['Easy', 'Medium', 'Hard'];
final List<String> levelLowercase = ['easy', 'medium', 'hard'];
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoadingScreen(
index: selectedIndex,
selectedDif: levelLowercase[difficulty],
)));
},
child: Container(
height: 50,
width: MediaQuery.of(context).size.width,
alignment: Alignment.center,
decoration: BoxDecoration(
color: cardDetailList[selectedIndex].shadowColor,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
offset: const Offset(3, 3),
blurRadius: 3,
color: Colors.white.withOpacity(0.3),
),
],
border: Border.all(
color: Colors.white,
),
),
child: Text(
level[difficulty],
style: const TextStyle(
color: Colors.white,
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
),
);
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/widgets/close_button.dart | import 'package:flutter/material.dart';
class CustomCloseButton extends StatelessWidget {
const CustomCloseButton({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.white),
),
child: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: const Icon(
Icons.close_rounded,
color: Colors.white,
size: 30,
),
),
);
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/widgets/list_card.dart | import 'package:flutter/material.dart';
import 'package:trivia_app/utility/card_details.dart';
import 'package:trivia_app/screens/difficulty_selection_screen.dart';
class ListCard extends StatelessWidget {
const ListCard(this.index);
final int index;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 200,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DifficultyScreen(
selectedIndex: index,
)),
);
},
child: Stack(
alignment: AlignmentDirectional.topEnd,
children: [
Container(
margin: const EdgeInsets.only(top: 50),
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
height: 150,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: cardDetailList[index].gradients,
),
borderRadius: BorderRadius.circular(30),
boxShadow: [
BoxShadow(
offset: const Offset(1, 3),
blurRadius: 7,
spreadRadius: 5,
color: cardDetailList[index].shadowColor,
)
],
),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
cardDetailList[index].title,
style: const TextStyle(
fontSize: 25,
color: Colors.white,
fontWeight: FontWeight.w700,
),
),
],
),
),
Hero(
tag: cardDetailList[index].iconTag,
child: Image.asset(
cardDetailList[index].iconAssetName,
scale: 3,
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/utility/card_details.dart | import 'package:flutter/material.dart';
class ListDetail {
ListDetail(
{required this.title,
required this.iconAssetName,
required this.gradients,
required this.shadowColor,
required this.iconTag,
required this.category,
required this.textColor});
final String title;
final String iconAssetName;
final List<Color> gradients;
final Color shadowColor;
final Object iconTag;
final String category;
final Color textColor;
}
const double opacity = 0.4;
final List<ListDetail> cardDetailList = [
ListDetail(
title: 'Art and Literature',
iconAssetName: 'assets/images/art and literature.png',
gradients: [
const Color(0xff089e44),
const Color(0xff3dd178),
],
shadowColor: const Color(0xff3dd178).withOpacity(opacity),
iconTag: 'art_icon',
category: 'arts_and_literature',
textColor: const Color(0xff089e44),
),
ListDetail(
title: 'Film and TV',
iconAssetName: 'assets/images/film and tv.png',
gradients: [
const Color(0xff5718d6),
const Color(0xff8048f0),
],
shadowColor: const Color(0xff8048f0).withOpacity(opacity),
iconTag: 'film_icon',
category: 'film_and_tv',
textColor: const Color(0xff5718d6),
),
ListDetail(
title: 'Food and Drink',
iconAssetName: 'assets/images/food and drink.png',
gradients: [
const Color(0xffd6182e),
const Color(0xffed475a),
],
shadowColor: const Color(0xffed475a).withOpacity(opacity),
iconTag: 'food_icon',
category: 'food_and_drink',
textColor: const Color(0xffd6182e),
),
ListDetail(
title: 'General Knowledge',
iconAssetName: 'assets/images/general knowledge.png',
gradients: [
const Color(0xff0846a3),
const Color(0xff387ee8),
],
shadowColor: const Color(0xff387ee8).withOpacity(opacity),
iconTag: 'gk_icon',
category: 'general_knowledge',
textColor: const Color(0xff0846a3),
),
ListDetail(
title: 'Geography',
iconAssetName: 'assets/images/geography.png',
gradients: [
const Color(0xffd97014),
const Color(0xfff2a057),
],
shadowColor: const Color(0xfff2a057).withOpacity(opacity),
iconTag: 'geography_icon',
category: 'geography',
textColor: const Color(0xffd97014),
),
ListDetail(
title: 'History',
iconAssetName: 'assets/images/history.png',
gradients: [
const Color(0xff1c0659),
const Color(0xff3c2a70),
],
shadowColor: const Color(0xff3c2a70).withOpacity(opacity),
iconTag: 'history_icon',
category: 'history',
textColor: const Color(0xff3c2a70),
),
ListDetail(
title: 'Music',
iconAssetName: 'assets/images/music.png',
gradients: [
const Color(0xff28272b),
const Color(0xff48474a),
],
shadowColor: const Color(0xff48474a).withOpacity(opacity),
iconTag: 'music_icon',
category: 'music',
textColor: const Color(0xff28272b),
),
ListDetail(
title: 'Science',
iconAssetName: 'assets/images/science.png',
gradients: [
const Color(0xffeb2aeb),
const Color(0xfffc7efc),
],
shadowColor: const Color(0xfffc7efc).withOpacity(opacity),
iconTag: 'science_icon',
category: 'science',
textColor: const Color(0xffeb2aeb),
),
ListDetail(
title: 'Society and Culture',
iconAssetName: 'assets/images/society and culture.png',
gradients: [
const Color(0xfff2bd05),
const Color(0xffe6c657),
],
shadowColor: const Color(0xffe6c657).withOpacity(opacity),
iconTag: 'society_icon',
category: 'society_and_culture',
textColor: const Color(0xfff2bd05),
),
ListDetail(
title: 'Sports and Leisure',
iconAssetName: 'assets/images/sports and leisure.png',
gradients: [
const Color(0xff395c91),
const Color(0xff75aafa),
],
shadowColor: const Color(0xff75aafa).withOpacity(opacity),
iconTag: 'sports_icon',
category: 'sport_and_leisure',
textColor: const Color(0xff395c91),
),
];
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/utility/questions.dart | class Question {
final String question;
final List<String> options;
final String correctAnswer;
Question({
required this.question,
required this.correctAnswer,
required this.options,
});
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/services/networking.dart | import 'dart:convert';
import 'package:http/http.dart' as http;
class NetworkHelper {
final String url;
NetworkHelper(this.url);
Future getData() async {
http.Response response = await http.get(Uri.parse(url));
String data = response.body;
return jsonDecode(data);
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/services/quiz_maker.dart | import 'package:trivia_app/utility/questions.dart';
class QuizMaker {
List<Question> _questionList = [];
int _score = 0;
List<String> _createOptions(dynamic json, int i) {
List<String> list = (json[i]['incorrectAnswers']).cast<String>();
list.add(json[i]['correctAnswer']);
list.shuffle();
return list;
}
int getCorrectIndex(int i) {
for (int j = 0; j < 4; j++) {
if (_questionList[i].options[j] == _questionList[i].correctAnswer) {
return j;
}
}
return 0;
}
void getList(dynamic json) {
for (int i = 0; i < 10; i++) {
_questionList.add(Question(
question: json[i]['question'],
correctAnswer: json[i]['correctAnswer'],
options: _createOptions(json, i),
));
}
}
String getQuestion(int i) {
return _questionList[i].question;
}
List<String> getOptions(int i) {
return _questionList[i].options;
}
bool isCorrect(int i, int selectedOption) {
if (_questionList[i].options[selectedOption] ==
_questionList[i].correctAnswer) return true;
return false;
}
void increaseScore() {
_score++;
}
int getScore() {
return _score;
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/screens/loading_screen.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:trivia_app/screens/question_screen.dart';
import 'package:trivia_app/utility/card_details.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:trivia_app/services/networking.dart';
class LoadingScreen extends StatefulWidget {
final int index;
final String selectedDif;
const LoadingScreen({required this.index, required this.selectedDif});
@override
State<LoadingScreen> createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
@override
void initState() {
super.initState();
SchedulerBinding.instance?.addPostFrameCallback((_) {
Timer(const Duration(milliseconds: 500), () {
getQuestions();
});
});
}
Future<bool> checkConnectivity() async {
bool result = await InternetConnectionChecker().hasConnection;
return result;
}
void getQuestions() async {
bool result = await checkConnectivity();
if (result) {
NetworkHelper networkHelper = NetworkHelper(
'https://the-trivia-api.com/api/questions?categories=' +
cardDetailList[widget.index].category +
'&limit=10&difficulty=' +
widget.selectedDif);
var questionData = await networkHelper.getData();
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => QuestionScreen(
questionData: questionData,
categoryIndex: widget.index,
)),
),
);
} else {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Error'),
content: const Text('No internet connection. Try again later.'),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
Navigator.pop(context);
},
child: const Text('Ok'),
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: cardDetailList[widget.index].gradients,
),
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Center(
child: LoadingAnimationWidget.halfTriangleDot(
color: Colors.white,
size: 50,
),
),
),
);
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/screens/difficulty_selection_screen.dart | import 'package:flutter/material.dart';
import 'package:trivia_app/utility/card_details.dart';
import 'package:trivia_app/widgets/close_button.dart';
import 'package:trivia_app/widgets/difficulty_tile.dart';
class DifficultyScreen extends StatelessWidget {
const DifficultyScreen({required this.selectedIndex});
final int selectedIndex;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(left: 20, right: 20, top: 40, bottom: 20),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: cardDetailList[selectedIndex].gradients,
),
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: const [
CustomCloseButton(),
],
),
Text(
cardDetailList[selectedIndex].title,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w900,
fontSize: 35,
),
),
Hero(
tag: cardDetailList[selectedIndex].iconTag,
child: Image.asset(
cardDetailList[selectedIndex].iconAssetName,
height: 300,
width: 300,
),
),
Column(
children: [
const Text(
'Select Difficulty',
style: TextStyle(
color: Colors.white,
fontSize: 25,
fontWeight: FontWeight.bold),
),
const SizedBox(height: 5),
Text(
'Harder the Difficulty, Lesser the Time per question.',
style: TextStyle(
color: Colors.white.withOpacity(0.5),
fontSize: 15,
fontWeight: FontWeight.bold),
),
],
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
DifficultyTile(selectedIndex: selectedIndex, difficulty: 0),
const SizedBox(height: 20),
DifficultyTile(selectedIndex: selectedIndex, difficulty: 1),
const SizedBox(height: 20),
DifficultyTile(selectedIndex: selectedIndex, difficulty: 2),
],
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/screens/home_screen.dart | import 'package:flutter/material.dart';
import 'package:trivia_app/widgets/list_card.dart';
import 'package:trivia_app/utility/card_details.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
physics: const ScrollPhysics(),
child: Container(
margin:
const EdgeInsets.only(top: 40, left: 20, right: 20, bottom: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
padding: const EdgeInsets.all(7),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.grey)),
child: const Icon(
Icons.favorite_sharp,
color: Colors.lightBlueAccent,
size: 30,
),
),
const SizedBox(width: 15),
Container(
padding: const EdgeInsets.all(7),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.grey)),
child: const Icon(
Icons.person,
color: Colors.lightBlueAccent,
size: 30,
),
),
],
),
const SizedBox(height: 10),
const Text(
'Let\'s play',
style: TextStyle(
fontSize: 40,
fontWeight: FontWeight.w900,
color: Color(0xfff85e7d),
),
),
const SizedBox(height: 5),
const Text(
'Be the fisrt!',
style: TextStyle(
fontSize: 20,
color: Color(0xffa9a4a5),
fontWeight: FontWeight.w700,
),
),
ListView.builder(
itemCount: cardDetailList.length,
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, index) {
return ListCard(index);
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/screens/score_screen.dart | import 'package:flutter/material.dart';
import 'package:fl_score_bar/fl_score_bar.dart';
import 'package:trivia_app/utility/card_details.dart';
class ScoreScreen extends StatelessWidget {
final int score;
final int index;
const ScoreScreen({Key? key, required this.score, required this.index})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: cardDetailList[index].gradients,
),
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconScoreBar(
scoreIcon: Icons.star_rounded,
iconColor: Colors.yellow,
score: score / 3,
maxScore: 3,
readOnly: true,
),
const SizedBox(height: 30),
Text(
'${score.toString()}/10',
style: const TextStyle(
fontSize: 40,
fontWeight: FontWeight.w800,
color: Colors.white,
),
),
const SizedBox(height: 30),
GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Container(
width: 0.3 * MediaQuery.of(context).size.width,
height: 0.08 * MediaQuery.of(context).size.height,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
offset: const Offset(1, 3),
blurRadius: 0.7,
color: Colors.grey.withOpacity(0.8),
),
],
),
child: Icon(
Icons.exit_to_app,
color: cardDetailList[index].textColor,
size: 30,
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Quizler/lib | mirrored_repositories/Quizler/lib/screens/question_screen.dart | import 'package:flutter/material.dart';
import 'package:circular_countdown_timer/circular_countdown_timer.dart';
import 'package:trivia_app/screens/score_screen.dart';
import 'package:trivia_app/services/quiz_maker.dart';
import 'package:trivia_app/utility/card_details.dart';
import 'package:trivia_app/widgets/close_button.dart';
class QuestionScreen extends StatefulWidget {
QuestionScreen({required this.questionData, required this.categoryIndex});
final questionData;
final int categoryIndex;
@override
State<QuestionScreen> createState() => _QuestionScreenState();
}
class _QuestionScreenState extends State<QuestionScreen> {
@override
void initState() {
super.initState();
quizMaker.getList(widget.questionData);
}
final CountDownController _controller = CountDownController();
QuizMaker quizMaker = QuizMaker();
int questionNumber = 0;
bool isAbsorbing = false;
final int duration = 10;
List<Color> optionColor = [
Colors.white,
Colors.white,
Colors.white,
Colors.white
];
List<Widget> buildOptions(int i) {
List<String> options = quizMaker.getOptions(i);
List<Widget> Options = [];
for (int j = 0; j < 4; j++) {
Options.add(OptionWidget(
widget: widget,
option: options[j],
optionColor: optionColor[j],
onTap: () async {
_controller.pause();
if (quizMaker.isCorrect(i, j)) {
setState(() {
optionColor[j] = Colors.green;
isAbsorbing = true;
});
quizMaker.increaseScore();
} else {
setState(() {
optionColor[j] = Colors.red;
optionColor[quizMaker.getCorrectIndex(i)] = Colors.green;
isAbsorbing = true;
});
}
await Future.delayed(
const Duration(seconds: 1, milliseconds: 30), () {});
if (questionNumber < 9) {
setState(() {
optionColor[j] = Colors.white;
optionColor[quizMaker.getCorrectIndex(i)] = Colors.white;
questionNumber++;
isAbsorbing = false;
});
_controller.restart();
} else {
Navigator.pop(context);
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ScoreScreen(
score: quizMaker.getScore(),
index: widget.categoryIndex,
),
),
);
}
},
));
}
return Options;
}
@override
Widget build(BuildContext context) {
return AbsorbPointer(
absorbing: isAbsorbing,
child: Container(
padding:
const EdgeInsets.only(left: 20, right: 20, top: 60, bottom: 20),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: cardDetailList[widget.categoryIndex].gradients,
),
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const CustomCloseButton(),
CircularCountDownTimer(
width: 50,
height: 50,
duration: duration,
fillColor: Colors.grey.withOpacity(0.8),
ringColor: Colors.white,
textStyle: const TextStyle(
fontSize: 25,
color: Colors.white,
fontWeight: FontWeight.bold,
),
autoStart: true,
isReverse: true,
controller: _controller,
onComplete: () {
if (questionNumber < 9) {
setState(() {
questionNumber++;
});
_controller.restart();
} else {
Navigator.pop(context);
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ScoreScreen(
score: quizMaker.getScore(),
index: widget.categoryIndex,
),
),
);
}
},
),
Container(
height: 35,
width: 35,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Colors.white,
),
),
child: const Icon(
Icons.favorite_sharp,
color: Colors.white,
),
),
],
),
SizedBox(
height: 200,
width: 300,
child: Image.asset(
cardDetailList[widget.categoryIndex].iconAssetName,
fit: BoxFit.fitHeight,
),
),
// ignore: prefer_const_constructors
SizedBox(
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'question ${(questionNumber + 1).toString()} of 10',
style: TextStyle(
color: Colors.white.withOpacity(0.6),
fontSize: 20,
),
),
const SizedBox(height: 10),
// ignore: prefer_const_constructors
Text(
quizMaker.getQuestion(questionNumber),
style: const TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
],
),
),
...buildOptions(questionNumber),
],
),
),
),
);
}
}
class OptionWidget extends StatelessWidget {
const OptionWidget(
{Key? key,
required this.widget,
required this.option,
required this.onTap,
required this.optionColor})
: super(key: key);
final QuestionScreen widget;
final String option;
final VoidCallback onTap;
final Color optionColor;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
alignment: Alignment.center,
height: 50,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: optionColor,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
offset: const Offset(1, 3),
blurRadius: 3,
color: Colors.black.withOpacity(0.3),
),
],
),
child: Text(
option,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: cardDetailList[widget.categoryIndex].textColor,
),
),
),
);
}
}
| 0 |
mirrored_repositories/Quizler | mirrored_repositories/Quizler/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:trivia_app/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/My_Applications/Flutter_Apps/app_2_startup_name | mirrored_repositories/My_Applications/Flutter_Apps/app_2_startup_name/lib/main.dart | import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart'; // Added this line from the dependencies list on the pubspec.yaml
// Next, you'll use the english_words package to generate the text instead of using the string "Hello World".
void main() => runApp(MyApp()); // The main method uses arrow (=>) notation. Use arrow notation for one-line functions or methods.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final wordPair = WordPair.random(); // Add this line.
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome to Flutter'),
),
body: Center(
// child: const Text('Hello World'), // replace the Hello World
child: Text(wordPair.asPascalCase), // with this text
// Tip: "Pascal case" (also known as "upper camel case"), means that each word in the string, including the first one, begins with an uppercase letter.
// So, "upper camel case" becomes "UpperCamelCase".
),
),
);
}
}
| 0 |
mirrored_repositories/My_Applications/Flutter_Apps/app_2_startup_name | mirrored_repositories/My_Applications/Flutter_Apps/app_2_startup_name/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:app_2_startup_name/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/My_Applications/Flutter_Apps/survey_app | mirrored_repositories/My_Applications/Flutter_Apps/survey_app/lib/main.dart | // importing this package gives us the dart widgets
// as well as the Material Theme widgets
import 'package:flutter/material.dart';
// The main() function is the starting point for every Flutter app.
void main() {}
| 0 |
mirrored_repositories/My_Applications/Flutter_Apps/survey_app | mirrored_repositories/My_Applications/Flutter_Apps/survey_app/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:survey_app/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/My_Applications/Flutter_Apps/hello_world_app | mirrored_repositories/My_Applications/Flutter_Apps/hello_world_app/lib/main.dart | import 'package:flutter/material.dart'; // imports the material.dart library that contains several widgets that follows the Matterial Design pattern
void main() { // this is the entry point of any flutter app -- main()
runApp(MyApp());
}
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: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
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>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0 |
mirrored_repositories/My_Applications/Flutter_Apps/hello_world_app | mirrored_repositories/My_Applications/Flutter_Apps/hello_world_app/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:hello_world_app/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/My_Applications/Flutter_Apps/list_view_widget | mirrored_repositories/My_Applications/Flutter_Apps/list_view_widget/lib/main.dart | // ListView Widget - The most common way to display lots of data
import 'package:flutter/material.dart';
void main() {
// runApp() is a builtin method that initializes the app layout
// MyApp() (see below) is a widget that will be the root of our application.
runApp(MyApp());
}
// the root widget of our application
class MyApp extends StatelessWidget {
// The build method rebuilds the widget tree if there are any changes
// and allows hot reload to work.
@override
Widget build(BuildContext context) {
// This time instead of using a Container we are using the MaterialApp
// widget, which is setup to make our app have the Material theme.
return MaterialApp(
// The Scaffold widget lays out our home page for us
home: Scaffold(
// We will pass an AppBar widget to the appBar property of Scaffold
appBar: AppBar(
// The AppBar property takes a Text widget for its title property
title: Text('Exploring Widgets'),
),
// The body property of the Scaffold widget is the main content of
// our screen. Instead of directly giving it a widget we are going
// to break it out into another method so that things don't get
// too messy here.
body: myWidget(),
),
);
}
}
// ListView Widget
Widget myWidget() {
return ListView.builder(
padding: EdgeInsets.all(16.0),
// spacing of the rows
itemExtent: 30.0,
// provides an infinite list
itemBuilder: (BuildContext context, int index) {
return Text('Row $index');
},
);
}
| 0 |
mirrored_repositories/My_Applications/Flutter_Apps/list_view_widget | mirrored_repositories/My_Applications/Flutter_Apps/list_view_widget/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:list_view_widget/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/My_Applications/Flutter_Apps/button_widget | mirrored_repositories/My_Applications/Flutter_Apps/button_widget/lib/main.dart | // Button Widget
import 'package:flutter/material.dart';
void main() {
// runApp() is a builtin method that initializes the app layout
// MyApp() (see below) is a widget that will be the root of our application.
runApp(MyApp());
}
// the root widget of our application
class MyApp extends StatelessWidget {
// The build method rebuilds the widget tree if there are any changes
// and allows hot reload to work.
@override
Widget build(BuildContext context) {
// This time instead of using a Container we are using the MaterialApp
// widget, which is setup to make our app have the Material theme.
return MaterialApp(
// The Scaffold widget lays out our home page for us
home: Scaffold(
// We will pass an AppBar widget to the appBar property of Scaffold
appBar: AppBar(
// The AppBar property takes a Text widget for its title property
title: Text('Exploring Widgets'),
),
// The body property of the Scaffold widget is the main content of
// our screen. Instead of directly giving it a widget we are going
// to break it out into another method so that things don't get
// too messy here.
body: myWidget(),
),
);
}
}
// This is where we will play with the Text widget
// button widget
Widget myWidget() {
return FlatButton(
child: const Text('Button'),
splashColor: Colors.green,
onPressed: () {
// do something
},
);
} | 0 |
mirrored_repositories/My_Applications/Flutter_Apps/button_widget | mirrored_repositories/My_Applications/Flutter_Apps/button_widget/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:button_widget/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/My_Applications/Flutter_Apps/container_widget_in_flutter | mirrored_repositories/My_Applications/Flutter_Apps/container_widget_in_flutter/lib/main.dart | // Container Widget is a holder for other widgets
// importing this package gives us the dart widgets
// as well as the Material Theme widgets
import 'package:flutter/material.dart';
// the main() function is the starting point for every Flutter project
void main() {
// calling this method (you guessed it) runs our app
runApp(
// runApp() takes any widget as an argument.
// This widget will be used as the layout.
// We will give it a Container widget this time.
Container(
color: Colors.redAccent// <- you can change this
),
);
}
| 0 |
mirrored_repositories/My_Applications/Flutter_Apps/container_widget_in_flutter | mirrored_repositories/My_Applications/Flutter_Apps/container_widget_in_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:container_widget_in_flutter/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/My_Applications/Flutter_Apps/text_field_widget | mirrored_repositories/My_Applications/Flutter_Apps/text_field_widget/lib/main.dart | // Text - Field Widget
// For accepting user text input you use a TextField widget
import 'package:flutter/material.dart';
void main() {
// runApp() is a builtin method that initializes the app layout
// MyApp() (see below) is a widget that will be the root of our application.
runApp(MyApp());
}
// the root widget of our application
class MyApp extends StatelessWidget {
// The build method rebuilds the widget tree if there are any changes
// and allows hot reload to work.
@override
Widget build(BuildContext context) {
// This time instead of using a Container we are using the MaterialApp
// widget, which is setup to make our app have the Material theme.
return MaterialApp(
// The Scaffold widget lays out our home page for us
home: Scaffold(
// We will pass an AppBar widget to the appBar property of Scaffold
appBar: AppBar(
// The AppBar property takes a Text widget for its title property
title: Text('Exploring Widgets'),
),
// The body property of the Scaffold widget is the main content of
// our screen. Instead of directly giving it a widget we are going
// to break it out into another method so that things don't get
// too messy here.
body: myWidget(),
),
);
}
}
// TextField Widget
Widget myWidget() {
return TextField(
decoration: InputDecoration(
//border: InputBorder.none, // you can uncomment this line to do away with the line
hintText: 'Write something here'
),
);
}
| 0 |
mirrored_repositories/My_Applications/Flutter_Apps/text_field_widget | mirrored_repositories/My_Applications/Flutter_Apps/text_field_widget/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:text_field_widget/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/My_Applications/Flutter_Apps/text_widget_in_flutter | mirrored_repositories/My_Applications/Flutter_Apps/text_widget_in_flutter/lib/main.dart | // Text widget
// Probably every single app that you make will have text,
// so the Text widget is definitely one that we need to look at.
import 'package:flutter/material.dart';
void main() {
// runApp() is a builtin method that initializes the app layout
// MyApp() (see below) is a widget that will be the root of our application.
runApp(MyApp());
}
// the root widget of our application
class MyApp extends StatelessWidget {
// The build method rebuilds the widget tree if there are any changes
// and allows hot reload to work.
@override
Widget build(BuildContext context) {
// This time instead of using a Container we are using the MaterialApp
// widget, which is setup to make our app have the Material theme.
return MaterialApp(
// The Scaffold widget lays out our home page for us
home: Scaffold(
// We will pass an AppBar widget to the appBar property of Scaffold
appBar: AppBar(
// The AppBar property takes a Text widget for its title property
title: Text('Exploring Widgets'),
),
// The body property of the Scaffold widget is the main content of
// our screen. Instead of directly giving it a widget we are going
// to break it out into another method so that things don't get
// too messy here.
body: myWidget(),
),
);
}
}
// This is where we will play with the Text widget
Widget myWidget() {
return Text(
"Hello World, I am exploring Text Widget", // change the output text
style: TextStyle(
fontSize: 30.0 // increase the font size
// There are lots of other changes you can make with the TextStyle widget,
// like color, font, shadows, and spacing to name a few.
),
);
}
| 0 |
mirrored_repositories/My_Applications/Flutter_Apps/text_widget_in_flutter | mirrored_repositories/My_Applications/Flutter_Apps/text_widget_in_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:text_widget_in_flutter/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/spacex-go | mirrored_repositories/spacex-go/lib/main.dart | import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:path_provider/path_provider.dart';
import 'cubits/index.dart';
import 'repositories/index.dart';
import 'services/index.dart';
import 'utils/index.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
HydratedBloc.storage = await HydratedStorage.build(
storageDirectory: kIsWeb
? HydratedStorage.webStorageDirectory
: await getTemporaryDirectory(),
);
Bloc.observer = CherryBlocObserver();
final httpClient = Dio();
final notificationsCubit = kIsWeb
? null
: NotificationsCubit(
FlutterLocalNotificationsPlugin(),
notificationDetails: NotificationDetails(
android: AndroidNotificationDetails(
'channel.launches',
'Launches notifications',
'Stay up-to-date with upcoming SpaceX launches',
importance: Importance.high,
),
iOS: IOSNotificationDetails(),
),
initializationSettings: InitializationSettings(
android: AndroidInitializationSettings('notification_launch'),
iOS: IOSInitializationSettings(),
),
);
await notificationsCubit?.init();
runApp(CherryApp(
notificationsCubit: notificationsCubit,
vehiclesRepository: VehiclesRepository(
VehiclesService(httpClient),
),
launchesRepository: LaunchesRepository(
LaunchesService(httpClient),
),
achievementsRepository: AchievementsRepository(
AchievementsService(httpClient),
),
companyRepository: CompanyRepository(
CompanyService(httpClient),
),
changelogRepository: ChangelogRepository(
ChangelogService(httpClient),
),
));
}
/// Builds the neccesary cubits, as well as the home page.
class CherryApp extends StatelessWidget {
final NotificationsCubit notificationsCubit;
final VehiclesRepository vehiclesRepository;
final LaunchesRepository launchesRepository;
final AchievementsRepository achievementsRepository;
final CompanyRepository companyRepository;
final ChangelogRepository changelogRepository;
const CherryApp({
this.notificationsCubit,
this.vehiclesRepository,
this.launchesRepository,
this.achievementsRepository,
this.companyRepository,
this.changelogRepository,
});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(create: (_) => ThemeCubit()),
BlocProvider(create: (_) => ImageQualityCubit()),
BlocProvider(create: (_) => BrowserCubit()),
BlocProvider.value(value: notificationsCubit),
BlocProvider(create: (_) => VehiclesCubit(vehiclesRepository)),
BlocProvider(create: (_) => LaunchesCubit(launchesRepository)),
BlocProvider(create: (_) => AchievementsCubit(achievementsRepository)),
BlocProvider(create: (_) => CompanyCubit(companyRepository)),
BlocProvider(create: (_) => ChangelogCubit(changelogRepository)),
],
child: BlocConsumer<ThemeCubit, ThemeState>(
listener: (context, state) => null,
builder: (context, state) => MaterialApp(
title: 'SpaceX GO!',
theme: context.watch<ThemeCubit>().lightTheme,
darkTheme: context.watch<ThemeCubit>().darkTheme,
themeMode: context.watch<ThemeCubit>().themeMode,
onGenerateRoute: Routes.generateRoute,
onUnknownRoute: Routes.errorRoute,
localizationsDelegates: [
FlutterI18nDelegate(
translationLoader: FileTranslationLoader(),
)..load(null),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
),
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/browser.dart | import 'package:hydrated_bloc/hydrated_bloc.dart';
enum BrowserType { inApp, system }
/// Supports browser type selection on the user side.
/// - The [BrowserType.inApp] will display the URL inside an 'in-app' browser tab,
/// using the system default web browser.
/// - The [BrowserType.system] will open the web page inside the system default
/// web browser.
class BrowserCubit extends HydratedCubit<BrowserType> {
static const defaultBrowser = BrowserType.inApp;
BrowserCubit() : super(defaultBrowser);
@override
BrowserType fromJson(Map<String, dynamic> json) {
return BrowserType.values[json['value']];
}
@override
Map<String, int> toJson(BrowserType state) {
return {
'value': state.index,
};
}
BrowserType get browserType => state;
set browserType(BrowserType browserType) => emit(browserType);
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/notifications.dart | import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import '../models/index.dart';
import '../utils/index.dart';
/// Serves as a way to communicate with the notification system.
class NotificationsCubit extends HydratedCubit<DateTime> {
final FlutterLocalNotificationsPlugin service;
final NotificationDetails notificationDetails;
final InitializationSettings initializationSettings;
NotificationsCubit(
this.service, {
this.notificationDetails,
this.initializationSettings,
}) : assert(service != null),
super(null);
/// Initializes the notifications system
Future<void> init() async {
try {
await service.initialize(initializationSettings);
} catch (_) {}
}
/// Saves the current target launch date
void setNextLaunchDate(DateTime date) => emit(date);
/// Clears previous set notifications if they exist
void clearPreviousNotifications() {
if (state != null) {
service.cancelAll();
}
}
/// Sets the target launch date to null
void resetNextLaunchDate() => emit(null);
/// Checks if it's necceasry to update scheduled notifications
bool needsToUpdate(DateTime date) => state != date;
/// Schedule new notifications
Future<void> scheduleNotification({
@required int id,
@required String title,
@required String body,
@required tz.TZDateTime dateTime,
}) async =>
service.zonedSchedule(
id,
title,
body,
dateTime,
notificationDetails,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.wallClockTime,
);
/// Method that handle the schedule of launch notifications over the time
Future<void> updateNotifications(
BuildContext context, {
@required Launch nextLaunch,
}) async {
try {
if (nextLaunch != null && needsToUpdate(nextLaunch.launchDate)) {
// Cancels all previous schedule notifications because the date has changed
clearPreviousNotifications();
// If the date and time of the next launch has been set
if (!nextLaunch.tentativeTime) {
tz.initializeTimeZones();
final utcLaunchDate = tz.TZDateTime.from(
nextLaunch.launchDate,
tz.UTC,
);
final utcCurrentDate = tz.TZDateTime.now(tz.UTC);
// T-1 day notification
if (utcCurrentDate.add(Duration(days: 1)).isBefore(utcLaunchDate)) {
await scheduleNotification(
id: 0,
title: context.translate(
'spacex.notifications.launches.title',
),
body: context.translate(
'spacex.notifications.launches.body',
parameters: {
'rocket': nextLaunch.rocket.name,
'payload': nextLaunch.rocket.getSinglePayload.name,
'orbit': nextLaunch.rocket.getSinglePayload.orbit,
'time': context.translate(
'spacex.notifications.launches.time_tomorrow',
),
},
),
dateTime: utcLaunchDate.subtract(Duration(days: 1)),
);
}
// T-1 hour notification
if (utcCurrentDate.add(Duration(hours: 1)).isBefore(utcLaunchDate)) {
await scheduleNotification(
id: 1,
title: context.translate(
'spacex.notifications.launches.title',
),
body: context.translate(
'spacex.notifications.launches.body',
parameters: {
'rocket': nextLaunch.rocket.name,
'payload': nextLaunch.rocket.getSinglePayload.name,
'orbit': nextLaunch.rocket.getSinglePayload.orbit,
'time': context.translate(
'spacex.notifications.launches.time_hour',
),
},
),
dateTime: utcLaunchDate.subtract(Duration(hours: 1)),
);
}
// T-30 minutes notification
if (utcCurrentDate.add(Duration(minutes: 30)).isBefore(
utcLaunchDate,
)) {
await scheduleNotification(
id: 2,
title: context.translate(
'spacex.notifications.launches.title',
),
body: context.translate(
'spacex.notifications.launches.body',
parameters: {
'rocket': nextLaunch.rocket.name,
'payload': nextLaunch.rocket.getSinglePayload.name,
'orbit': nextLaunch.rocket.getSinglePayload.orbit,
'time': context.translate(
'spacex.notifications.launches.time_minutes',
parameters: {
'minutes': '30',
},
),
},
),
dateTime: utcLaunchDate.subtract(Duration(minutes: 30)),
);
}
setNextLaunchDate(nextLaunch.launchDate);
} else {
resetNextLaunchDate();
}
}
} catch (_) {}
}
@override
DateTime fromJson(Map<String, dynamic> json) {
return json['value'] != null ? DateTime.tryParse(json['value']) : null;
}
@override
Map<String, String> toJson(DateTime state) {
return {
'value': state?.toIso8601String(),
};
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/launches.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../models/index.dart';
import '../repositories/index.dart';
import '../utils/index.dart';
/// Cubit that holds a list of launches.
class LaunchesCubit
extends RequestCubit<LaunchesRepository, List<List<Launch>>> {
LaunchesCubit(LaunchesRepository repository) : super(repository);
@override
Future<void> loadData() async {
emit(RequestState.loading(state.value));
try {
final data = await repository.fetchData();
emit(RequestState.loaded(data));
} catch (e) {
emit(RequestState.error(e.toString()));
}
}
Launch getLaunch(String id) {
if (state.status == RequestStatus.loaded) {
return LaunchUtils.getAllLaunches(state.value)
.where((l) => l.id == id)
.single;
} else {
return null;
}
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/vehicles.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../models/index.dart';
import '../repositories/index.dart';
/// Cubit that holds a list of SpaceX vehicles.
class VehiclesCubit extends RequestCubit<VehiclesRepository, List<Vehicle>> {
VehiclesCubit(VehiclesRepository repository) : super(repository);
@override
Future<void> loadData() async {
emit(RequestState.loading(state.value));
try {
final data = await repository.fetchData();
emit(RequestState.loaded(data));
} catch (e) {
emit(RequestState.error(e.toString()));
}
}
Vehicle getVehicle(String id) {
if (state.status == RequestStatus.loaded) {
return state.value.where((l) => l.id == id).single;
} else {
return null;
}
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/index.dart | export 'achievements.dart';
export 'browser.dart';
export 'changelog.dart';
export 'company.dart';
export 'image_quality.dart';
export 'index.dart';
export 'launches.dart';
export 'notifications.dart';
export 'theme.dart';
export 'vehicles.dart';
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/image_quality.dart | import 'package:hydrated_bloc/hydrated_bloc.dart';
enum ImageQuality { low, medium, high }
/// Saves and loads information regarding the image quality setting.
class ImageQualityCubit extends HydratedCubit<ImageQuality> {
static const defaultQuality = ImageQuality.medium;
ImageQualityCubit() : super(defaultQuality);
@override
ImageQuality fromJson(Map<String, dynamic> json) {
return ImageQuality.values[json['value']];
}
@override
Map<String, int> toJson(ImageQuality state) {
return {
'value': state.index,
};
}
ImageQuality get imageQuality => state;
set imageQuality(ImageQuality imageQuality) => emit(imageQuality);
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/achievements.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../models/index.dart';
import '../repositories/index.dart';
/// Cubit that holds a list of all achievements scored in SpaceX history.
class AchievementsCubit
extends RequestCubit<AchievementsRepository, List<Achievement>> {
AchievementsCubit(AchievementsRepository repository) : super(repository);
@override
Future<void> loadData() async {
emit(RequestState.loading(state.value));
try {
final data = await repository.fetchData();
emit(RequestState.loaded(data));
} catch (e) {
emit(RequestState.error(e.toString()));
}
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/theme.dart | import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import '../utils/index.dart';
enum ThemeState { light, dark, black, system }
final Map<ThemeState, ThemeData> _themeData = {
ThemeState.light: Style.light,
ThemeState.dark: Style.dark,
ThemeState.black: Style.black,
};
/// Saves and loads information regarding the theme setting.
class ThemeCubit extends HydratedCubit<ThemeState> {
static const defaultTheme = ThemeState.system;
ThemeCubit() : super(defaultTheme);
@override
ThemeState fromJson(Map<String, dynamic> json) {
return ThemeState.values[json['value']];
}
@override
Map<String, int> toJson(ThemeState state) {
return {
'value': state.index,
};
}
ThemeState get theme => state;
set theme(ThemeState themeState) => emit(themeState);
/// Returns appropiate theme mode
ThemeMode get themeMode {
switch (state) {
case ThemeState.light:
return ThemeMode.light;
case ThemeState.dark:
case ThemeState.black:
return ThemeMode.dark;
default:
return ThemeMode.system;
}
}
/// Default light theme
ThemeData get lightTheme => _themeData[ThemeState.light];
/// Default dark theme
ThemeData get darkTheme => state == ThemeState.black
? _themeData[ThemeState.black]
: _themeData[ThemeState.dark];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/company.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../models/index.dart';
import '../repositories/index.dart';
/// Cubit that holds information about SpaceX.
class CompanyCubit extends RequestCubit<CompanyRepository, CompanyInfo> {
CompanyCubit(CompanyRepository repository) : super(repository);
@override
Future<void> loadData() async {
emit(RequestState.loading(state.value));
try {
final data = await repository.fetchData();
emit(RequestState.loaded(data));
} catch (e) {
emit(RequestState.error(e.toString()));
}
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/cubits/changelog.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../repositories/index.dart';
/// Cubit that holds information about the changelog of this app.
class ChangelogCubit
extends RequestPersistantCubit<ChangelogRepository, String> {
ChangelogCubit(ChangelogRepository repository) : super(repository);
@override
Future<void> loadData() async {
emit(RequestState.loading(state.value));
try {
final data = await repository.fetchData();
emit(RequestState.loaded(data));
} catch (e) {
emit(RequestState.error(e.toString()));
}
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/payload.dart | import 'package:equatable/equatable.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
import 'index.dart';
/// Specific details about an one-of-a-kink space payload.
class Payload extends Equatable {
final CapsuleDetails capsule;
final String name;
final bool reused;
final String customer;
final String nationality;
final String manufacturer;
final num mass;
final String orbit;
final num periapsis;
final num apoapsis;
final num inclination;
final num period;
final String id;
const Payload({
this.capsule,
this.name,
this.reused,
this.customer,
this.nationality,
this.manufacturer,
this.mass,
this.orbit,
this.periapsis,
this.apoapsis,
this.inclination,
this.period,
this.id,
});
factory Payload.fromJson(Map<String, dynamic> json) {
return Payload(
capsule: json['dragon']['capsule'] != null
? CapsuleDetails.fromJson(json['dragon']['capsule'])
: null,
name: json['name'],
reused: json['reused'],
customer: (json['customers'] as List).isNotEmpty
? (json['customers'] as List).first
: null,
nationality: (json['nationalities'] as List).isNotEmpty
? (json['nationalities'] as List).first
: null,
manufacturer: (json['manufacturers'] as List).isNotEmpty
? (json['manufacturers'] as List).first
: null,
mass: json['mass_kg'],
orbit: json['orbit'],
periapsis: json['periapsis_km'],
apoapsis: json['apoapsis_km'],
inclination: json['inclination_deg'],
period: json['period_min'],
id: json['id'],
);
}
String getName(BuildContext context) =>
name ?? context.translate('spacex.other.unknown');
String getCustomer(BuildContext context) =>
customer ?? context.translate('spacex.other.unknown');
String getNationality(BuildContext context) =>
nationality ?? context.translate('spacex.other.unknown');
String getManufacturer(BuildContext context) =>
manufacturer ?? context.translate('spacex.other.unknown');
String getOrbit(BuildContext context) =>
orbit ?? context.translate('spacex.other.unknown');
String getMass(BuildContext context) => mass == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(mass)} kg';
String getPeriapsis(BuildContext context) => periapsis == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(periapsis.round())} km';
String getApoapsis(BuildContext context) => apoapsis == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(apoapsis.round())} km';
String getInclination(BuildContext context) => inclination == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(inclination.round())}°';
String getPeriod(BuildContext context) => period == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(period.round())} min';
bool get isNasaPayload =>
customer == 'NASA (CCtCap)' ||
customer == 'NASA (CRS)' ||
customer == 'NASA(COTS)';
@override
List<Object> get props => [
capsule,
name,
reused,
customer,
nationality,
manufacturer,
mass,
orbit,
periapsis,
apoapsis,
inclination,
period,
id,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/launchpad.dart | import 'package:equatable/equatable.dart';
import 'package:intl/intl.dart';
import 'package:latlong2/latlong.dart';
/// Details about a specific launchpad, where rockets are launched from.
class LaunchpadDetails extends Equatable {
final String name;
final String fullName;
final String locality;
final String region;
final double latitude;
final double longitude;
final int launchAttempts;
final int launchSuccesses;
final String status;
final String details;
final String imageUrl;
final String id;
const LaunchpadDetails({
this.name,
this.fullName,
this.locality,
this.region,
this.latitude,
this.longitude,
this.launchAttempts,
this.launchSuccesses,
this.status,
this.details,
this.imageUrl,
this.id,
});
factory LaunchpadDetails.fromJson(Map<String, dynamic> json) {
return LaunchpadDetails(
name: json['name'],
fullName: json['full_name'],
locality: json['locality'],
region: json['region'],
latitude: json['latitude'],
longitude: json['longitude'],
launchAttempts: json['launch_attempts'],
launchSuccesses: json['launch_successes'],
status: json['status'],
details: json['details'],
imageUrl: json['images']['large'][0],
id: json['id'],
);
}
LatLng get coordinates => LatLng(latitude, longitude);
String get getStatus => toBeginningOfSentenceCase(status);
String get getCoordinates =>
'${coordinates.latitude.toStringAsPrecision(5)}, ${coordinates.longitude.toStringAsPrecision(5)}';
String get getSuccessfulLaunches => '$launchSuccesses/$launchAttempts';
@override
List<Object> get props => [
name,
fullName,
locality,
region,
latitude,
longitude,
launchAttempts,
launchSuccesses,
details,
id,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/dragon_vehicle.dart | import 'package:equatable/equatable.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
import 'index.dart';
/// General information about a Dragon capsule.
class DragonVehicle extends Vehicle {
final num crew, launchMass, returnMass;
final List<Thruster> thrusters;
final bool reusable;
const DragonVehicle({
String id,
String name,
String type,
String description,
String url,
num height,
num diameter,
num mass,
bool active,
DateTime firstFlight,
List<String> photos,
this.crew,
this.launchMass,
this.returnMass,
this.thrusters,
this.reusable,
}) : super(
id: id,
name: name,
type: type,
description: description,
url: url,
height: height,
diameter: diameter,
mass: mass,
active: active,
firstFlight: firstFlight,
photos: photos,
);
factory DragonVehicle.fromJson(Map<String, dynamic> json) {
return DragonVehicle(
id: json['id'],
name: json['name'],
type: json['type'],
description: json['description'],
url: json['wikipedia'],
height: json['height_w_trunk']['meters'],
diameter: json['diameter']['meters'],
mass: json['dry_mass_kg'],
active: json['active'],
firstFlight: DateTime.parse(json['first_flight']),
photos: json['flickr_images'].cast<String>(),
crew: json['crew_capacity'],
launchMass: json['launch_payload_mass']['kg'],
returnMass: json['return_payload_mass']['kg'],
thrusters: [
for (final item in json['thrusters']) Thruster.fromJson(item)
],
reusable: true,
);
}
@override
String subtitle(BuildContext context) => firstLaunched(context);
bool get isCrewEnabled => crew != 0;
String getCrew(BuildContext context) => isCrewEnabled
? context.translate(
'spacex.vehicle.capsule.description.people',
parameters: {'people': crew.toString()},
)
: context.translate('spacex.vehicle.capsule.description.no_people');
String get getLaunchMass =>
'${NumberFormat.decimalPattern().format(launchMass)} kg';
String get getReturnMass =>
'${NumberFormat.decimalPattern().format(returnMass)} kg';
@override
List<Object> get props => [
id,
name,
type,
description,
url,
height,
diameter,
mass,
active,
firstFlight,
photos,
crew,
launchMass,
returnMass,
thrusters,
reusable,
];
}
/// Auxiliar model used to storage Dragon's thrusters data.
class Thruster extends Equatable {
final String model;
final String fuel;
final String oxidizer;
final num amount;
final num thrust;
final num isp;
const Thruster({
this.model,
this.fuel,
this.oxidizer,
this.amount,
this.thrust,
this.isp,
});
factory Thruster.fromJson(Map<String, dynamic> json) {
return Thruster(
model: json['type'],
fuel: json['fuel_2'],
oxidizer: json['fuel_1'],
amount: json['amount'],
thrust: json['thrust']['kN'],
isp: json['isp'],
);
}
String get getFuel => toBeginningOfSentenceCase(fuel);
String get getOxidizer => toBeginningOfSentenceCase(oxidizer);
String get getAmount => amount.toString();
String get getThrust => '${NumberFormat.decimalPattern().format(thrust)} kN';
String get getIsp => '${NumberFormat.decimalPattern().format(isp)} s';
@override
List<Object> get props => [
model,
fuel,
oxidizer,
amount,
thrust,
isp,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/landpad.dart | import 'package:equatable/equatable.dart';
import 'package:intl/intl.dart';
import 'package:latlong2/latlong.dart';
/// Details about a specific landpad,
/// where boosters can land after completing its mission.
class LandpadDetails extends Equatable {
final String name;
final String fullName;
final String type;
final String locality;
final String region;
final double latitude;
final double longitude;
final int landingAttempts;
final int landingSuccesses;
final String wikipediaUrl;
final String details;
final String status;
final String imageUrl;
final String id;
const LandpadDetails({
this.name,
this.fullName,
this.type,
this.locality,
this.region,
this.latitude,
this.longitude,
this.landingAttempts,
this.landingSuccesses,
this.wikipediaUrl,
this.details,
this.status,
this.imageUrl,
this.id,
});
factory LandpadDetails.fromJson(Map<String, dynamic> json) {
return LandpadDetails(
name: json['name'],
fullName: json['full_name'],
type: json['type'],
locality: json['locality'],
region: json['region'],
latitude: json['latitude'],
longitude: json['longitude'],
landingAttempts: json['landing_attempts'],
landingSuccesses: json['landing_successes'],
wikipediaUrl: json['wikipedia'],
details: json['details'],
status: json['status'],
imageUrl: json['images']['large'][0],
id: json['id'],
);
}
LatLng get coordinates => LatLng(latitude, longitude);
String get getStatus => toBeginningOfSentenceCase(status);
String get getCoordinates =>
'${coordinates.latitude.toStringAsPrecision(5)}, ${coordinates.longitude.toStringAsPrecision(5)}';
String get getSuccessfulLandings => '$landingSuccesses/$landingAttempts';
@override
List<Object> get props => [
name,
fullName,
type,
locality,
region,
latitude,
longitude,
landingAttempts,
landingSuccesses,
wikipediaUrl,
details,
status,
id,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/launch_details.dart | import 'package:equatable/equatable.dart';
/// Storages basic details about a rocket launch.
/// It serves as a direct link to its details.
class LaunchDetails extends Equatable {
final int flightNumber;
final String name;
final DateTime date;
final String id;
const LaunchDetails({
this.flightNumber,
this.name,
this.date,
this.id,
});
factory LaunchDetails.fromJson(Map<String, dynamic> json) {
return LaunchDetails(
flightNumber: json['flight_number'],
name: json['name'],
date: json['date_utc'] != null ? DateTime.parse(json['date_utc']) : null,
id: json['id'],
);
}
DateTime get localDate => date.toLocal();
@override
List<Object> get props => [
flightNumber,
name,
date,
id,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/launch.dart | import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
import 'index.dart';
/// Details about a specific launch, performed by a Falcon rocket,
/// including launch & landing pads, rocket & payload information...
class Launch extends Equatable implements Comparable<Launch> {
final String patchUrl;
final List<String> links;
final List<String> photos;
final DateTime staticFireDate;
final int launchWindow;
final bool success;
final FailureDetails failure;
final String details;
final RocketDetails rocket;
final LaunchpadDetails launchpad;
final int flightNumber;
final String name;
final DateTime launchDate;
final String datePrecision;
final bool upcoming;
final String id;
const Launch({
this.patchUrl,
this.links,
this.photos,
this.staticFireDate,
this.launchWindow,
this.success,
this.failure,
this.details,
this.rocket,
this.launchpad,
this.flightNumber,
this.name,
this.launchDate,
this.datePrecision,
this.upcoming,
this.id,
});
factory Launch.fromJson(Map<String, dynamic> json) {
return Launch(
patchUrl: json['links']['patch']['small'],
links: [
json['links']['webcast'],
json['links']['reddit']['campaign'],
json['links']['presskit']
],
photos: (json['links']['flickr']['original'] as List).cast<String>(),
staticFireDate: json['static_fire_date_utc'] != null
? DateTime.tryParse(json['static_fire_date_utc'])
: null,
launchWindow: json['window'],
success: json['success'],
failure: (json['failures'] as List).isNotEmpty
? FailureDetails.fromJson((json['failures'] as List).first)
: null,
details: json['details'],
rocket: RocketDetails.fromJson(json),
launchpad: LaunchpadDetails.fromJson(json['launchpad']),
flightNumber: json['flight_number'],
name: json['name'],
launchDate:
json['date_utc'] != null ? DateTime.tryParse(json['date_utc']) : null,
datePrecision: json['date_precision'],
upcoming: json['upcoming'],
id: json['id'],
);
}
@override
int compareTo(Launch other) => flightNumber.compareTo(other.flightNumber);
String getLaunchWindow(BuildContext context) {
if (launchWindow == null) {
return context.translate('spacex.other.unknown');
} else if (launchWindow == 0) {
return context.translate(
'spacex.launch.page.rocket.instantaneous_window',
);
} else if (launchWindow < 60) {
return '$launchWindow s';
} else if (launchWindow < 3600) {
return '${(launchWindow / 60).truncate()} min';
} else if (launchWindow % 3600 == 0) {
return '${(launchWindow / 3600).truncate()} h';
} else {
return '${(launchWindow ~/ 3600).truncate()}h ${((launchWindow / 3600 - launchWindow ~/ 3600) * 60).truncate()}min';
}
}
DateTime get localLaunchDate => launchDate?.toLocal();
DateTime get localStaticFireDate => staticFireDate?.toLocal();
String get getNumber => '#${NumberFormat('00').format(flightNumber)}';
bool get hasPatch => patchUrl != null;
bool get hasVideo => links[0] != null;
String get getVideo => links[0];
bool get tentativeTime => datePrecision != 'hour';
String getDetails(BuildContext context) =>
details ?? context.translate('spacex.launch.page.no_description');
String getLaunchDate(BuildContext context) {
switch (datePrecision) {
case 'hour':
return context.translate(
'spacex.other.date.time',
parameters: {
'date': getTentativeDate,
'hour': getTentativeTime,
},
);
default:
return context.translate(
'spacex.other.date.upcoming',
parameters: {'date': getTentativeDate},
);
}
}
String get getTentativeDate {
switch (datePrecision) {
case 'hour':
return DateFormat.yMMMMd().format(localLaunchDate);
case 'day':
return DateFormat.yMMMMd().format(localLaunchDate);
case 'month':
return DateFormat.yMMMM().format(localLaunchDate);
case 'quarter':
return DateFormat.yQQQ().format(localLaunchDate);
case 'half':
return 'H${localLaunchDate.month < 7 ? 1 : 2} ${localLaunchDate.year}';
case 'year':
return DateFormat.y().format(localLaunchDate);
default:
return 'date error';
}
}
String get getShortTentativeTime => DateFormat.Hm().format(localLaunchDate);
String get getTentativeTime =>
'$getShortTentativeTime ${localLaunchDate.timeZoneName}';
bool get isDateTooTentative =>
datePrecision != 'hour' && datePrecision != 'day';
String getStaticFireDate(BuildContext context) => staticFireDate == null
? context.translate('spacex.other.unknown')
: DateFormat.yMMMMd().format(localStaticFireDate);
String get year => localLaunchDate.year.toString();
static int getMenuIndex(String url) => Menu.launch.indexOf(url) + 1;
bool isUrlEnabled(String url) => links[getMenuIndex(url)] != null;
String getUrl(String name) => links[getMenuIndex(name)];
bool get hasPhotos => photos.isNotEmpty;
bool get avoidedStaticFire => !upcoming && staticFireDate == null;
@override
List<Object> get props => [
patchUrl,
links,
photos,
staticFireDate,
launchWindow,
success,
failure,
details,
rocket,
launchpad,
flightNumber,
name,
launchDate,
datePrecision,
upcoming,
id,
];
}
/// Auxiliary model to storage all details about a rocket which performed a SpaceX's mission.
class RocketDetails extends Equatable {
final FairingsDetails fairings;
final List<Core> cores;
final List<Payload> payloads;
final String name;
final String id;
const RocketDetails({
this.fairings,
this.cores,
this.payloads,
this.name,
this.id,
});
factory RocketDetails.fromJson(Map<String, dynamic> json) {
return RocketDetails(
fairings: json['fairings'] != null
? FairingsDetails.fromJson(json['fairings'])
: null,
cores:
(json['cores'] as List).map((core) => Core.fromJson(core)).toList(),
payloads: (json['payloads'] as List)
.map((payload) => Payload.fromJson(payload))
.toList(),
name: json['rocket']['name'],
id: json['rocket']['id'],
);
}
bool get isHeavy => cores.length != 1;
bool get hasFairings => fairings != null;
Core get getSingleCore => cores[0];
bool isSideCore(Core core) {
if (id == null || !isHeavy) {
return false;
} else {
return core != cores.first;
}
}
bool get isFirstStageNull {
for (final core in cores) {
if (core.id != null) return false;
}
return true;
}
bool get hasMultiplePayload => payloads.length > 1;
Payload get getSinglePayload => payloads[0];
bool get hasCapsule => getSinglePayload.capsule != null;
Core getCore(String id) => cores.where((core) => core.id == id).single;
@override
List<Object> get props => [
fairings,
cores,
payloads,
name,
id,
];
}
/// Auxiliary model to storage details about rocket's fairings.
class FairingsDetails extends Equatable {
final bool reused;
final bool recoveryAttempt;
final bool recovered;
const FairingsDetails({
this.reused,
this.recoveryAttempt,
this.recovered,
});
factory FairingsDetails.fromJson(Map<String, dynamic> json) {
return FairingsDetails(
reused: json['reused'],
recoveryAttempt: json['recovery_attempt'],
recovered: json['recovered'],
);
}
@override
List<Object> get props => [
reused,
recoveryAttempt,
recovered,
];
}
/// Auxiliar model to storage details about a launch failure.
class FailureDetails extends Equatable {
final num time;
final num altitude;
final String reason;
const FailureDetails({this.time, this.altitude, this.reason});
factory FailureDetails.fromJson(Map<String, dynamic> json) {
return FailureDetails(
time: json['time'],
altitude: json['altitude'],
reason: json['reason'],
);
}
String get getTime {
final StringBuffer buffer = StringBuffer('T${time.isNegative ? '-' : '+'}');
final int auxTime = time.abs();
if (auxTime < 60) {
buffer.write('${NumberFormat.decimalPattern().format(auxTime)} s');
} else if (auxTime < 3600) {
buffer.write(
'${NumberFormat.decimalPattern().format(auxTime ~/ 60)}min ${NumberFormat.decimalPattern().format(auxTime - (auxTime ~/ 60 * 60))}s');
} else {
buffer.write(
'${NumberFormat.decimalPattern().format(auxTime ~/ 3600)}h ${NumberFormat.decimalPattern().format((auxTime / 3600 - auxTime ~/ 3600) * 60)}min');
}
return buffer.toString();
}
String getAltitude(BuildContext context) => altitude == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(altitude)} km';
String get getReason => toBeginningOfSentenceCase(reason);
@override
List<Object> get props => [
time,
altitude,
reason,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/core.dart | import 'package:equatable/equatable.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
import 'index.dart';
/// Auxiliary model to storage details about a core in a particular mission.
class Core extends Equatable {
final int block;
final int reuseCount;
final int rtlsAttempts;
final int rtlsLandings;
final int asdsAttempts;
final int asdsLandings;
final String lastUpdate;
final List<LaunchDetails> launches;
final String serial;
final String status;
final String id;
final String landingType;
final bool hasGridfins;
final bool hasLegs;
final bool reused;
final bool landingAttempt;
final bool landingSuccess;
final LandpadDetails landpad;
const Core({
this.block,
this.reuseCount,
this.rtlsAttempts,
this.rtlsLandings,
this.asdsAttempts,
this.asdsLandings,
this.lastUpdate,
this.launches,
this.serial,
this.status,
this.id,
this.landingType,
this.hasGridfins,
this.hasLegs,
this.reused,
this.landingAttempt,
this.landingSuccess,
this.landpad,
});
factory Core.fromJson(Map<String, dynamic> json) {
return Core(
block: json['core'] != null ? json['core']['block'] : null,
reuseCount: json['core'] != null ? json['core']['reuse_count'] : null,
rtlsAttempts: json['core'] != null ? json['core']['rtls_attempts'] : null,
rtlsLandings: json['core'] != null ? json['core']['rtls_landings'] : null,
asdsAttempts: json['core'] != null ? json['core']['asds_attempts'] : null,
asdsLandings: json['core'] != null ? json['core']['asds_landings'] : null,
lastUpdate: json['core'] != null ? json['core']['last_update'] : null,
launches: json['core'] != null
? (json['core']['launches'] as List)
.map((launch) => LaunchDetails.fromJson(launch))
.toList()
: null,
serial: json['core'] != null ? json['core']['serial'] : null,
status: json['core'] != null ? json['core']['status'] : null,
id: json['core'] != null ? json['core']['id'] : null,
landingType: json['landing_type'],
hasGridfins: json['gridfins'],
hasLegs: json['legs'],
reused: json['reused'],
landingAttempt: json['landing_attempt'],
landingSuccess: json['landing_success'],
landpad: json['landpad'] != null
? LandpadDetails.fromJson(json['landpad'])
: null,
);
}
String get getStatus => toBeginningOfSentenceCase(status);
String getFirstLaunched(BuildContext context) => launches.isNotEmpty
? DateFormat.yMMMMd().format(launches.first.localDate)
: context.translate('spacex.other.unknown');
String get getLaunches => launches.length.toString();
bool get hasMissions => launches.isNotEmpty;
String getDetails(BuildContext context) =>
lastUpdate ??
context.translate('spacex.dialog.vehicle.no_description_core');
String getBlock(BuildContext context) =>
getBlockData(context) ?? context.translate('spacex.other.unknown');
String getBlockData(BuildContext context) => block != null
? context.translate(
'spacex.other.block',
parameters: {'block': block.toString()},
)
: null;
String get getRtlsLandings => '$rtlsLandings/$rtlsAttempts';
String get getAsdsLandings => '$asdsLandings/$asdsAttempts';
@override
List<Object> get props => [
block,
reuseCount,
rtlsAttempts,
rtlsLandings,
asdsAttempts,
asdsLandings,
lastUpdate,
launches,
serial,
status,
id,
hasGridfins,
hasLegs,
reused,
landingAttempt,
landingSuccess,
landpad,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/roadster_vehicle.dart | import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
import 'index.dart';
/// Details about Elon Musk's Tesla Roadster launched on top of a Falcon Heavy
/// at February 6, 2018. Currently orbiting the Sun, between Earth & Mars.
class RoadsterVehicle extends Vehicle {
final String orbit;
final String video;
final num apoapsis;
final num periapsis;
final num inclination;
final num longitude;
final num period;
final num speed;
final num earthDistance;
final num marsDistance;
const RoadsterVehicle({
String id,
String description,
String url,
num mass,
DateTime firstFlight,
List<String> photos,
this.orbit,
this.video,
this.apoapsis,
this.periapsis,
this.inclination,
this.longitude,
this.period,
this.speed,
this.earthDistance,
this.marsDistance,
}) : super(
id: id,
name: 'Tesla Roadster',
type: 'roadster',
description: description,
url: url,
mass: mass,
firstFlight: firstFlight,
photos: photos,
);
factory RoadsterVehicle.fromJson(Map<String, dynamic> json) {
return RoadsterVehicle(
id: json['id'],
description: json['details'],
url: json['wikipedia'],
mass: json['launch_mass_kg'],
firstFlight: DateTime.parse(json['launch_date_utc']),
photos: json['flickr_images'].cast<String>(),
orbit: json['orbit_type'],
video: json['video'],
apoapsis: json['apoapsis_au'],
periapsis: json['periapsis_au'],
inclination: json['inclination'],
longitude: json['longitude'],
period: json['period_days'],
speed: json['speed_kph'],
earthDistance: json['earth_distance_km'],
marsDistance: json['mars_distance_km'],
);
}
@override
String subtitle(BuildContext context) => getFullLaunchDate(context);
String getFullLaunchDate(BuildContext context) => context.translate(
'spacex.vehicle.subtitle.launched',
parameters: {'date': getLaunchDate(context)},
);
String getLaunchDate(BuildContext context) =>
DateFormat.yMMMMd().format(firstFlight);
String get getOrbit => toBeginningOfSentenceCase(orbit);
String get getApoapsis =>
'${NumberFormat.decimalPattern().format(apoapsis)} ua';
String get getPeriapsis =>
'${NumberFormat.decimalPattern().format(periapsis)} ua';
String get getInclination =>
'${NumberFormat.decimalPattern().format(inclination)}°';
String get getLongitude =>
'${NumberFormat.decimalPattern().format(longitude)}°';
String getPeriod(BuildContext context) => context.translate(
'spacex.vehicle.roadster.orbit.days',
parameters: {
'days': NumberFormat.decimalPattern().format(period.round())
},
);
String get getSpeed =>
'${NumberFormat.decimalPattern().format(speed.round())} km/h';
String get getEarthDistance =>
'${NumberFormat.decimalPattern().format(earthDistance.round())} km';
String get getMarsDistance =>
'${NumberFormat.decimalPattern().format(marsDistance.round())} km';
@override
List<Object> get props => [
id,
description,
url,
mass,
firstFlight,
photos,
orbit,
video,
apoapsis,
periapsis,
inclination,
longitude,
period,
speed,
earthDistance,
marsDistance,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/ship_vehicle.dart | import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
import 'index.dart';
/// General information about a ship used by SpaceX.
class ShipVehicle extends Vehicle {
final String model;
final String use;
final String homePort;
final String status;
final List<String> roles;
final List<LaunchDetails> missions;
final num speed;
const ShipVehicle({
String id,
String name,
String url,
num mass,
bool active,
DateTime firstFlight,
List<String> photos,
this.model,
this.use,
this.roles,
this.missions,
this.homePort,
this.status,
this.speed,
}) : super(
id: id,
name: name,
type: 'ship',
url: url,
mass: mass,
active: active,
firstFlight: firstFlight,
photos: photos,
);
factory ShipVehicle.fromJson(Map<String, dynamic> json) {
return ShipVehicle(
id: json['id'],
name: json['name'],
url: json['link'],
mass: json['mass_kg'],
active: json['active'],
firstFlight: DateTime(json['year_built']),
photos: [json['image']].cast<String>(),
model: json['model'],
use: json['type'],
roles: json['roles'].cast<String>(),
missions: [
for (final item in json['launches']) LaunchDetails.fromJson(item)
],
homePort: json['home_port'],
status: json['status'],
speed: json['speed_kn'],
);
}
@override
String subtitle(BuildContext context) => context.translate(
'spacex.vehicle.subtitle.ship_built',
parameters: {'date': firstFlight.year.toString()},
);
String getModel(BuildContext context) =>
model ?? context.translate('spacex.other.unknown');
bool get hasSeveralRoles => roles.length > 1;
String get primaryRole => roles[0];
String get secondaryRole => roles[1];
bool get hasMissions => missions.isNotEmpty;
String getStatus(BuildContext context) => status?.isNotEmpty == true
? status
: context.translate('spacex.other.unknown');
String get getBuiltFullDate => year;
String getSpeed(BuildContext context) => speed == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(speed * 1.852)} km/h';
@override
List<Object> get props => [
id,
name,
url,
mass,
active,
firstFlight,
photos,
model,
use,
roles,
missions,
homePort,
status,
speed,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/index.dart | export 'achievement.dart';
export 'capsule_details.dart';
export 'company_info.dart';
export 'core.dart';
export 'dragon_vehicle.dart';
export 'landpad.dart';
export 'launch.dart';
export 'launch_details.dart';
export 'launchpad.dart';
export 'payload.dart';
export 'roadster_vehicle.dart';
export 'rocket_vehicle.dart';
export 'ship_vehicle.dart';
export 'vehicle.dart';
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/achievement.dart | import 'package:equatable/equatable.dart';
import 'package:intl/intl.dart';
/// Auxiliary model to storage specific SpaceX's achievments.
class Achievement extends Equatable {
final String id, name, details, url;
final DateTime date;
const Achievement({
this.id,
this.name,
this.details,
this.url,
this.date,
});
factory Achievement.fromJson(Map<String, dynamic> json) {
return Achievement(
id: json['id'],
name: json['title'],
details: json['details'],
url: json['links']['article'],
date: DateTime.parse(json['event_date_utc']),
);
}
String get getDate => DateFormat.yMMMMd().format(date);
bool get hasLink => url != null;
@override
List<Object> get props => [
id,
name,
details,
url,
date,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/capsule_details.dart | import 'package:equatable/equatable.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
import 'index.dart';
// Details about a specific capsule used in a CRS mission
class CapsuleDetails extends Equatable {
final int reuseCount;
final int splashings;
final String lastUpdate;
final List<LaunchDetails> launches;
final String serial;
final String status;
final String type;
final String id;
const CapsuleDetails({
this.reuseCount,
this.splashings,
this.lastUpdate,
this.launches,
this.serial,
this.status,
this.type,
this.id,
});
factory CapsuleDetails.fromJson(Map<String, dynamic> json) {
return CapsuleDetails(
reuseCount: json['reuse_count'],
splashings: json['water_landings'],
lastUpdate: json['last_update'],
launches: (json['launches'] as List)
.map((launch) => LaunchDetails.fromJson(launch))
.toList(),
serial: json['serial'],
status: json['status'],
type: json['type'],
id: json['id'],
);
}
String get getStatus => toBeginningOfSentenceCase(status);
String getFirstLaunched(BuildContext context) => launches.isNotEmpty
? DateFormat.yMMMMd().format(launches.first.localDate)
: context.translate('spacex.other.unknown');
String get getLaunches => launches.length.toString();
bool get hasMissions => launches.isNotEmpty;
String getDetails(BuildContext context) =>
lastUpdate ??
context.translate('spacex.dialog.vehicle.no_description_capsule');
String get getSplashings => splashings.toString();
@override
List<Object> get props => [
reuseCount,
splashings,
lastUpdate,
launches,
serial,
status,
type,
id,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/vehicle.dart | import 'dart:math';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
/// Details about a specific SpaceX vehicle.
/// Vehicles are considered Roadster, Dragons & Falcons, and ships.
abstract class Vehicle extends Equatable {
final String id;
final String name;
final String type;
final String description;
final String url;
final num height;
final num diameter;
final num mass;
final bool active;
final DateTime firstFlight;
final List<String> photos;
const Vehicle({
this.id,
this.name,
this.type,
this.description,
this.url,
this.height,
this.diameter,
this.mass,
this.active,
this.firstFlight,
this.photos,
});
String subtitle(BuildContext context);
String getPhoto(int index) => photos[index];
String get getProfilePhoto => getPhoto(0);
String getRandomPhoto([Random random]) {
final rng = random ?? Random();
return photos[rng.nextInt(photos.length)];
}
String get getHeight => '${NumberFormat.decimalPattern().format(height)} m';
String get getDiameter =>
'${NumberFormat.decimalPattern().format(diameter)} m';
String getMass(BuildContext context) => mass == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(mass)} kg';
String get getFirstFlight => DateFormat.yMMMM().format(firstFlight);
String get getFullFirstFlight => DateTime.now().isAfter(firstFlight)
? DateFormat.yMMMMd().format(firstFlight)
: getFirstFlight;
String firstLaunched(BuildContext context) => context.translate(
DateTime.now().isAfter(firstFlight)
? 'spacex.vehicle.subtitle.first_launched'
: 'spacex.vehicle.subtitle.scheduled_launch',
parameters: {'date': getFirstFlight},
);
String get year => firstFlight.year.toString();
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/company_info.dart | import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
/// General information about SpaceX's company data.
/// Used in the 'Company' tab, under the SpaceX screen.
class CompanyInfo extends Equatable {
final String city;
final String state;
final String fullName;
final String name;
final String founder;
final int founded;
final int employees;
final String ceo;
final String cto;
final String coo;
final num valuation;
final String details;
final String id;
const CompanyInfo({
this.city,
this.state,
this.fullName,
this.name,
this.founder,
this.founded,
this.employees,
this.ceo,
this.cto,
this.coo,
this.valuation,
this.details,
this.id,
});
factory CompanyInfo.fromJson(Map<String, dynamic> json) {
return CompanyInfo(
city: json['headquarters']['city'],
state: json['headquarters']['state'],
fullName: 'Space Exploration Technologies Corporation',
name: json['name'],
founder: json['founder'],
founded: json['founded'],
employees: json['employees'],
ceo: json['ceo'],
cto: json['cto'],
coo: json['coo'],
valuation: json['valuation'],
details: json['summary'],
id: json['id'],
);
}
String getFounderDate(BuildContext context) => context.translate(
'spacex.company.founded',
parameters: {
'founded': founded.toString(),
'founder': founder,
},
);
String get getValuation =>
NumberFormat.currency(symbol: '\$', decimalDigits: 0).format(valuation);
String get getLocation => '$city, $state';
String get getEmployees => NumberFormat.decimalPattern().format(employees);
@override
List<Object> get props => [
city,
state,
fullName,
name,
founder,
founded,
employees,
ceo,
cto,
coo,
valuation,
details,
id,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/models/rocket_vehicle.dart | import 'package:equatable/equatable.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import '../utils/index.dart';
import 'index.dart';
/// General information about a Falcon rocket.
class RocketVehicle extends Vehicle {
final num stages, launchCost, successRate;
final List<PayloadWeight> payloadWeights;
final Engine engine;
final Stage firstStage, secondStage;
final List<double> fairingDimensions;
const RocketVehicle({
String id,
String name,
String type,
String description,
String url,
num height,
num diameter,
num mass,
bool active,
DateTime firstFlight,
List<String> photos,
this.stages,
this.launchCost,
this.successRate,
this.payloadWeights,
this.engine,
this.firstStage,
this.secondStage,
this.fairingDimensions,
}) : super(
id: id,
name: name,
type: type,
description: description,
url: url,
height: height,
diameter: diameter,
mass: mass,
active: active,
firstFlight: firstFlight,
photos: photos,
);
factory RocketVehicle.fromJson(Map<String, dynamic> json) {
return RocketVehicle(
id: json['id'],
name: json['name'],
type: json['type'],
description: json['description'],
url: json['wikipedia'],
height: json['height']['meters'],
diameter: json['diameter']['meters'],
mass: json['mass']['kg'],
active: json['active'],
firstFlight: DateTime.parse(json['first_flight']),
photos: json['flickr_images'].cast<String>(),
stages: json['stages'],
launchCost: json['cost_per_launch'],
successRate: json['success_rate_pct'],
payloadWeights: [
for (final payloadWeight in json['payload_weights'])
PayloadWeight.fromJson(payloadWeight)
],
engine: Engine.fromJson(json['engines']),
firstStage: Stage.fromJson(json['first_stage']),
secondStage: Stage.fromJson(json['second_stage']),
fairingDimensions: [
json['second_stage']['payloads']['composite_fairing']['height']
['meters'],
json['second_stage']['payloads']['composite_fairing']['diameter']
['meters'],
],
);
}
@override
String subtitle(BuildContext context) => firstLaunched(context);
String getStages(BuildContext context) => context.translate(
'spacex.vehicle.rocket.specifications.stages',
parameters: {'stages': stages.toString()},
);
String get getLaunchCost =>
NumberFormat.currency(symbol: "\$", decimalDigits: 0).format(launchCost);
String getSuccessRate(BuildContext context) =>
DateTime.now().isAfter(firstFlight)
? NumberFormat.percentPattern().format(successRate / 100)
: context.translate('spacex.other.no_data');
String fairingHeight(BuildContext context) => fairingDimensions[0] == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(fairingDimensions[0])} m';
String fairingDiameter(BuildContext context) => fairingDimensions[1] == null
? context.translate('spacex.other.unknown')
: '${NumberFormat.decimalPattern().format(fairingDimensions[1])} m';
@override
List<Object> get props => [
id,
name,
type,
description,
url,
height,
diameter,
mass,
active,
firstFlight,
photos,
stages,
launchCost,
successRate,
payloadWeights,
engine,
firstStage,
secondStage,
fairingDimensions,
];
}
/// Auxiliar model used to storage rocket's engine data.
class Engine extends Equatable {
final num thrustSea;
final num thrustVacuum;
final num thrustToWeight;
final num ispSea;
final num ispVacuum;
final String name;
final String fuel;
final String oxidizer;
const Engine({
this.thrustSea,
this.thrustVacuum,
this.thrustToWeight,
this.ispSea,
this.ispVacuum,
this.name,
this.fuel,
this.oxidizer,
});
factory Engine.fromJson(Map<String, dynamic> json) {
return Engine(
thrustSea: json['thrust_sea_level']['kN'],
thrustVacuum: json['thrust_vacuum']['kN'],
thrustToWeight: json['thrust_to_weight'],
ispSea: json['isp']['sea_level'],
ispVacuum: json['isp']['vacuum'],
name: '${json['type']} ${json['version']}',
fuel: json['propellant_2'],
oxidizer: json['propellant_1'],
);
}
String get getThrustSea =>
'${NumberFormat.decimalPattern().format(thrustSea)} kN';
String get getThrustVacuum =>
'${NumberFormat.decimalPattern().format(thrustVacuum)} kN';
String getThrustToWeight(BuildContext context) => thrustToWeight == null
? context.translate('spacex.other.unknown')
: NumberFormat.decimalPattern().format(thrustToWeight);
String get getIspSea => '${NumberFormat.decimalPattern().format(ispSea)} s';
String get getIspVacuum =>
'${NumberFormat.decimalPattern().format(ispVacuum)} s';
String get getName => toBeginningOfSentenceCase(name);
String get getFuel => toBeginningOfSentenceCase(fuel);
String get getOxidizer => toBeginningOfSentenceCase(oxidizer);
@override
List<Object> get props => [
thrustSea,
thrustVacuum,
thrustToWeight,
ispSea,
ispVacuum,
name,
fuel,
oxidizer,
];
}
/// Auxiliary model to storage specific orbit & payload capability.
class PayloadWeight extends Equatable {
final String name;
final int mass;
const PayloadWeight(this.name, this.mass);
factory PayloadWeight.fromJson(Map<String, dynamic> json) {
return PayloadWeight(json['name'], json['kg']);
}
String get getMass => '${NumberFormat.decimalPattern().format(mass)} kg';
@override
List<Object> get props => [
name,
mass,
];
}
/// General information about a specific stage of a Falcon rocket.
class Stage extends Equatable {
final bool reusable;
final num engines;
final num fuelAmount;
final num thrust;
const Stage({
this.reusable,
this.engines,
this.fuelAmount,
this.thrust,
});
factory Stage.fromJson(Map<String, dynamic> json) {
return Stage(
reusable: json['reusable'],
engines: json['engines'],
fuelAmount: json['fuel_amount_tons'],
thrust: (json['thrust_sea_level'] ?? json['thrust'])['kN'],
);
}
String getEngines(BuildContext context) => context.translate(
engines == 1
? 'spacex.vehicle.rocket.stage.engine_number'
: 'spacex.vehicle.rocket.stage.engines_number',
parameters: {'number': engines.toString()},
);
String getFuelAmount(BuildContext context) => context.translate(
'spacex.vehicle.rocket.stage.fuel_amount_tons',
parameters: {'tons': NumberFormat.decimalPattern().format(fuelAmount)},
);
String get getThrust => '${NumberFormat.decimalPattern().format(thrust)} kN';
@override
List<Object> get props => [
reusable,
engines,
fuelAmount,
thrust,
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/repositories/launches.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../models/index.dart';
import '../services/index.dart';
/// Handles retrieve and transformation of [Launch] from the API, both past & future ones.
class LaunchesRepository
extends BaseRepository<LaunchesService, List<List<Launch>>> {
LaunchesRepository(LaunchesService service) : super(service);
@override
Future<List<List<Launch>>> fetchData() async {
final response = await service.getLaunches();
final launches = [
for (final item in response.data['docs']) Launch.fromJson(item)
]..sort();
return [
launches.where((l) => l.upcoming).toList(),
launches.where((l) => !l.upcoming).toList().reversed.toList()
];
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/repositories/vehicles.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../models/index.dart';
import '../services/index.dart';
/// Handles retrieve and transformation of [Vehicles] from the API.
/// This includes:
/// - Elon's Tesla Roadster car.
/// - Dragon capsules information.
/// - Rocket vehicles information.
/// - Various active ships information.
class VehiclesRepository
extends BaseRepository<VehiclesService, List<Vehicle>> {
VehiclesRepository(VehiclesService service) : super(service);
@override
Future<List<Vehicle>> fetchData() async {
final roadsterResponse = await service.getRoadster();
final dragonResponse = await service.getDragons();
final rocketResponse = await service.getRockets();
final shipResponse = await service.getShips();
return [
RoadsterVehicle.fromJson(roadsterResponse.data),
for (final item in dragonResponse.data['docs'])
DragonVehicle.fromJson(item),
for (final item in rocketResponse.data['docs'])
RocketVehicle.fromJson(item),
for (final item in shipResponse.data['docs']) ShipVehicle.fromJson(item),
];
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/repositories/index.dart | export 'achievements.dart';
export 'changelog.dart';
export 'company.dart';
export 'launches.dart';
export 'vehicles.dart';
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/repositories/achievements.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../models/index.dart';
import '../services/index.dart';
/// Handles retrieve and transformation of [Achievement] from the API.
class AchievementsRepository
extends BaseRepository<AchievementsService, List<Achievement>> {
AchievementsRepository(AchievementsService service) : super(service);
@override
Future<List<Achievement>> fetchData() async {
final response = await service.getAchievements();
return [for (final item in response.data) Achievement.fromJson(item)];
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/repositories/company.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../models/index.dart';
import '../services/index.dart';
/// Handles retrieve and transformation of [ComapnyInfo] from the API.
class CompanyRepository extends BaseRepository<CompanyService, CompanyInfo> {
const CompanyRepository(CompanyService service) : super(service);
@override
Future<CompanyInfo> fetchData() async {
final response = await service.getCompanyInformation();
return CompanyInfo.fromJson(response.data);
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/repositories/changelog.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../services/index.dart';
/// Handles retrieve and transformation of the changelog of the app.
class ChangelogRepository extends BaseRepository<ChangelogService, String> {
const ChangelogRepository(ChangelogService service) : super(service);
@override
Future<String> fetchData() async {
final response = await service.getChangelog();
return response.data;
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/browser.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_web_browser/flutter_web_browser.dart';
import 'package:url_launcher/url_launcher.dart';
import '../cubits/index.dart';
extension OpenURL on BuildContext {
Future<dynamic> openUrl(String url) {
if (read<BrowserCubit>().browserType == BrowserType.inApp) {
return FlutterWebBrowser.openWebPage(
url: url,
customTabsOptions: CustomTabsOptions(
instantAppsEnabled: true,
showTitle: true,
),
);
} else {
return canLaunch(url)
.then((_) => launch(url))
// ignore: return_of_invalid_type_from_catch_error
.catchError((error) => error);
}
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/menu.dart | import '../ui/views/general/index.dart';
/// Contains all possible popupmenus' strings
class Menu {
static const home = {
'app.menu.about': AboutScreen.route,
'app.menu.settings': SettingsScreen.route,
};
static const launch = [
'spacex.launch.menu.reddit',
'spacex.launch.menu.press_kit',
];
static const wikipedia = [
'spacex.other.menu.wikipedia',
];
static const ship = [
'spacex.other.menu.marine_traffic',
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/routes.dart | import 'package:flutter/material.dart';
import '../ui/views/general/index.dart';
import '../ui/views/launches/index.dart';
import '../ui/views/vehicles/index.dart';
import '../ui/widgets/index.dart';
/// Class that holds both route names & generate methods.
/// Used by the Flutter routing system
class Routes {
/// Methods that generate all routes
static Route<dynamic> generateRoute(RouteSettings routeSettings) {
try {
final Map<String, dynamic> args = routeSettings.arguments;
switch (routeSettings.name) {
case StartScreen.route:
return MaterialPageRoute(
settings: routeSettings,
builder: (_) => StartScreen(),
);
case AboutScreen.route:
return MaterialPageRoute(
settings: routeSettings,
builder: (_) => AboutScreen(),
);
case ChangelogScreen.route:
return MaterialPageRoute(
settings: routeSettings,
builder: (_) => ChangelogScreen(),
);
case SettingsScreen.route:
return MaterialPageRoute(
settings: routeSettings,
builder: (_) => SettingsScreen(),
);
case LaunchPage.route:
final id = args['id'] as String;
return MaterialPageRoute(
settings: routeSettings,
builder: (_) => LaunchPage(id),
);
case CorePage.route:
final launchId = args['launchId'] as String;
final coreId = args['coreId'] as String;
return ResponsivePageRoute(
settings: routeSettings,
builder: (_) => CorePage(
launchId: launchId,
coreId: coreId,
),
);
case CapsulePage.route:
final launchId = args['launchId'] as String;
return ResponsivePageRoute(
settings: routeSettings,
builder: (_) => CapsulePage(launchId: launchId),
);
case LaunchpadPage.route:
final launchId = args['launchId'] as String;
return ResponsivePageRoute(
settings: routeSettings,
builder: (_) => LaunchpadPage(launchId: launchId),
);
case LandpadPage.route:
final launchId = args['launchId'] as String;
final coreId = args['coreId'] as String;
return ResponsivePageRoute(
settings: routeSettings,
builder: (_) => LandpadPage(
launchId: launchId,
coreId: coreId,
),
);
case VehiclePage.route:
final id = args['id'] as String;
return MaterialPageRoute(
settings: routeSettings,
builder: (_) => VehiclePage(vehicleId: id),
);
default:
return errorRoute(routeSettings);
}
} catch (_) {
return errorRoute(routeSettings);
}
}
/// Method that calles the error screen when neccesary
static Route<dynamic> errorRoute(RouteSettings routeSettings) {
return MaterialPageRoute(
settings: routeSettings,
builder: (_) => ErrorScreen(),
);
}
}
class ResponsivePageRoute extends PageRouteBuilder {
ResponsivePageRoute({
RouteSettings settings,
@required WidgetBuilder builder,
Color barrierColor = const Color(0x80000000),
Duration transitionDuration = const Duration(milliseconds: 200),
Curve transitionCurve = Curves.linear,
}) : super(
settings: settings,
pageBuilder: (context, animation, _) => FadeTransition(
opacity: CurvedAnimation(
parent: animation,
curve: transitionCurve,
),
child: ResponsivePage(child: builder(context)),
),
transitionDuration: transitionDuration,
reverseTransitionDuration: transitionDuration,
opaque: false,
barrierDismissible: true,
barrierColor: barrierColor,
fullscreenDialog: true,
);
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/api_query.dart | /// This API queries helps to decide the info to be returned by the API.
/// Helps to reduce downloaded data size.
class ApiQuery {
static const launch = {
'options': {
'pagination': false,
'select': {
'links.patch.large': 0,
'links.reddit.launch': 0,
'links.reddit.media': 0,
'links.reddit.recovery': 0,
'links.flickr.small': 0,
'links.youtube_id': 0,
'links.article': 0,
'links.wikipedia': 0,
'fairings.ships': 0,
'tbd': 0,
'net': 0,
'static_fire_date_unix': 0,
'auto_update': 0,
'date_unix': 0,
'date_local': 0,
'ships': 0,
'capsules': 0,
'crew': 0,
},
'populate': [
{
'path': 'rocket',
'select': {
'name': 1,
}
},
{
'path': 'launchpad',
'select': {
'rockets': 0,
'launches': 0,
'timezone': 0,
}
},
{
'path': 'payloads',
'select': {
'type': 0,
'launch': 0,
'norad_ids': 0,
'mass_lbs': 0,
'longitude': 0,
'semi_major_axis_km': 0,
'eccentricity': 0,
'lifespan_years': 0,
'epoch': 0,
'regime': 0,
'mean_motion': 0,
'raan': 0,
'arg_of_pericenter': 0,
'mean_anomaly': 0,
'reference_system': 0,
'dragon.mass_returned_lbs': 0,
'dragon.mass_returned_kg': 0,
'dragon.flight_time_sec': 0,
'dragon.manifest': 0,
'dragon.water_landing': 0,
'dragon.land_landing': 0
},
'populate': {
'path': 'dragon.capsule',
'select': {
'mass_returned_lbs': 0,
'land_landings': 0,
},
'populate': {
'path': 'launches',
'select': {
'name': 1,
'flight_number': 1,
'date_utc': 1,
}
}
}
},
{
'path': 'cores',
'select': {
'flight': 0,
},
'populate': [
{
'path': 'core',
'populate': {
'path': 'launches',
'select': {
'name': 1,
'flight_number': 1,
'date_utc': 1,
}
}
},
{
'path': 'landpad',
'select': {
'launches': 0,
}
}
]
}
]
}
};
static const dragonVehicle = {
'options': {
'pagination': false,
'select': {
'heat_shield': 0,
'launch_payload_vol': 0,
'return_payload_vol': 0,
'pressurized_capsule': 0,
'trunk': 0,
'sidewall_angle_deg': 0,
'orbit_duration_yr': 0,
'dry_mass_lb': 0,
'launch_payload_mass.lb': 0,
'return_payload_mass.lb': 0,
'height_w_trunk.feet': 0,
'diameter.feet': 0,
'thrusters.pods': 0,
'thrusters.thrust.lbf': 0
}
}
};
static const roadsterVehicle = {
'options': {
'pagination': false,
'select': {
'name': 0,
'launch_date_unix': 0,
'launch_mass_lbs': 0,
'norad_id': 0,
'epoch_jd': 0,
'semi_major_axis_au': 0,
'eccentricity': 0,
'speed_mph': 0,
'earth_distance_mi': 0,
'mars_distance_mi': 0,
'periapsis_arg': 0
}
}
};
static const rocketVehicle = {
'options': {
'pagination': false,
'select': {
'height.feet': 0,
'diameter.feet': 0,
'mass.lb': 0,
'first_stage.thrust_sea_level.lbf': 0,
'first_stage.thrust_vacuum.lbf': 0,
'first_stage.burn_time_sec': 0,
'second_stage.thrust.lbf': 0,
'second_stage.payloads.composite_fairing.height.feet': 0,
'second_stage.payloads.composite_fairing.diameter.feet': 0,
'second_stage.payloads.option_1': 0,
'second_stage.burn_time_sec': 0,
'engines.thrust_sea_level.lbf': 0,
'engines.thrust_vacuum.lbf': 0,
'engines.number': 0,
'engines.layout': 0,
'engines.engine_loss_max': 0,
'payload_weights.lb': 0,
'landing_legs': 0,
'country': 0,
'company': 0
}
}
};
static const shipVehicle = {
'query': {
'active': true,
},
'options': {
'pagination': false,
'select': {
'legacy_id': 0,
'mmsi': 0,
'abs': 0,
'class': 0,
'mass_lbs': 0,
'course_deg': 0,
'last_ais_update': 0,
'imo': 0,
'active': 0
},
'populate': [
{
'path': 'launches',
'select': {
'flight_number': 1,
'name': 1,
}
}
]
}
};
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/style.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'colors.dart';
/// Class that contains all the different styles of an app
class Style {
/// Custom page transitions
static final _pageTransitionsTheme = PageTransitionsTheme(
builders: const {
TargetPlatform.android: ZoomPageTransitionsBuilder(),
TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
},
);
/// Light style
static final ThemeData light = ThemeData(
brightness: Brightness.light,
appBarTheme: AppBarTheme(brightness: Brightness.dark),
colorScheme: ColorScheme.light().copyWith(
primary: lightAccentColor,
secondary: lightAccentColor,
onSecondary: Colors.white,
),
primaryColor: lightPrimaryColor,
accentColor: lightAccentColor,
pageTransitionsTheme: _pageTransitionsTheme,
textTheme: GoogleFonts.rubikTextTheme(ThemeData.light().textTheme),
popupMenuTheme: PopupMenuThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
);
/// Dark style
static final ThemeData dark = ThemeData(
brightness: Brightness.dark,
colorScheme: ColorScheme.dark().copyWith(
primary: darkAccentColor,
secondary: darkAccentColor,
),
primaryColor: darkPrimaryColor,
accentColor: darkAccentColor,
canvasColor: darkCanvasColor,
scaffoldBackgroundColor: darkBackgroundColor,
cardColor: darkCardColor,
dividerColor: darkDividerColor,
dialogBackgroundColor: darkCardColor,
pageTransitionsTheme: _pageTransitionsTheme,
textTheme: GoogleFonts.rubikTextTheme(ThemeData.dark().textTheme),
popupMenuTheme: PopupMenuThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
);
/// Black style (OLED)
static final ThemeData black = ThemeData(
brightness: Brightness.dark,
colorScheme: ColorScheme.dark().copyWith(
primary: blackAccentColor,
secondary: blackAccentColor,
),
primaryColor: blackPrimaryColor,
accentColor: blackAccentColor,
canvasColor: blackPrimaryColor,
scaffoldBackgroundColor: blackPrimaryColor,
cardColor: blackPrimaryColor,
dividerColor: darkDividerColor,
dialogBackgroundColor: darkCardColor,
pageTransitionsTheme: _pageTransitionsTheme,
textTheme: GoogleFonts.rubikTextTheme(ThemeData.dark().textTheme),
popupMenuTheme: PopupMenuThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
side: BorderSide(color: darkDividerColor),
),
),
);
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/index.dart | export 'api_query.dart';
export 'bloc_observer.dart';
export 'browser.dart';
export 'colors.dart';
export 'launch_utils.dart';
export 'menu.dart';
export 'photos.dart';
export 'routes.dart';
export 'style.dart';
export 'translate.dart';
export 'url.dart';
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/bloc_observer.dart | import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CherryBlocObserver extends BlocObserver {
@override
void onCreate(BlocBase bloc) {
super.onCreate(bloc);
debugPrint('onCreate: ${bloc.runtimeType}');
}
@override
void onChange(BlocBase bloc, Change change) {
super.onChange(bloc, change);
debugPrint('onChange: ${bloc.runtimeType}, $change');
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
super.onError(bloc, error, stackTrace);
debugPrint('onError: ${bloc.runtimeType}, $error');
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/launch_utils.dart | import '../models/index.dart';
/// Useful methods used for perform various tasks inside a list of `Launch` objects.
class LaunchUtils {
/// Returs the most upcoming launch inside a list, if the list
/// is sorted by date.
static Launch getUpcomingLaunch(List<List<Launch>> launches) {
if (launches != null) {
return launches[0].first;
} else {
return null;
}
}
/// Returs the most latest launch inside a list, if the list
/// is sorted by date.
static Launch getLatestLaunch(List<List<Launch>> launches) {
if (launches != null) {
return launches[1].first;
} else {
return null;
}
}
/// Returns all launches combined into one single list.
static List<Launch> getAllLaunches(List<List<Launch>> launches) {
if (launches != null) {
return List.from([...launches[0], ...launches[1]]);
} else {
return null;
}
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/colors.dart | import 'package:flutter/material.dart';
/// Contains app colors to used them all around the app
// Light theme
const lightPrimaryColor = Color(0xFF1E1E1E);
const lightAccentColor = Color(0xFF1E5185);
// Dark theme
const darkPrimaryColor = Color(0xFF121212);
const darkAccentColor = Color(0xFFDFAB00);
const darkBackgroundColor = Color(0xFF1F1F1F);
const darkCanvasColor = Color(0xFF242424);
const darkCardColor = Color(0xFF272727);
const darkDividerColor = Color(0xFF545454);
// Black theme
const blackPrimaryColor = Color(0xFF000000);
const blackAccentColor = Color(0xFFFFFFFF);
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/photos.dart | /// Lays all photos' URL, used around the app
class SpaceXPhotos {
static const home = [
'https://live.staticflickr.com/65535/48954138922_9c42173f08_c.jpg',
'https://live.staticflickr.com/4615/40143096241_11128929df_c.jpg',
'https://live.staticflickr.com/7826/32774791628_785b3f71a6_c.jpg',
'https://live.staticflickr.com/7834/40628437283_e41cbaf1f2_c.jpg',
];
static const upcoming = [
'https://live.staticflickr.com/1781/41281636860_eb0a8ea174_c.jpg',
'https://live.staticflickr.com/293/32312415025_6841e30bf1_c.jpg',
'https://live.staticflickr.com/4483/37610547226_c8002032bc_c.jpg',
'https://live.staticflickr.com/4235/35359372730_99255c4a20_c.jpg',
'https://live.staticflickr.com/4696/40126460511_b15bf84c85_c.jpg',
];
static const company = [
'https://live.staticflickr.com/342/18039170043_e2ca8b540a_c.jpg',
'https://live.staticflickr.com/1829/42374725534_b6a1e441a9_c.jpg',
'https://live.staticflickr.com/8688/17024507155_2168c8d032_c.jpg',
'https://live.staticflickr.com/4760/40126462231_97a02f6f8c_c.jpg',
];
static const cores = [
'https://live.staticflickr.com/934/41868222930_641ecacef9_c.jpg',
'https://live.staticflickr.com/7135/27042449393_5782749d32_c.jpg',
'https://live.staticflickr.com/4654/25254688767_83c0563d06_c.jpg',
'https://live.staticflickr.com/4834/32040174268_edff615574_c.jpg',
'https://live.staticflickr.com/4887/31180979107_2ebe84196f_c.jpg',
];
static const capsules = [
'https://live.staticflickr.com/2815/32761844973_4b55b27d3c_c.jpg',
'https://live.staticflickr.com/3878/32761843663_9d8e818586_c.jpg',
'https://live.staticflickr.com/1602/24159153709_96bd13e171_c.jpg',
];
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/url.dart | /// Has all urls used in the app as static const strings.
class Url {
//Base URLs
static const spacexBaseUrl = 'https://api.spacexdata.com';
// Vechiles URLs
static const rockets = '$spacexBaseUrl/v4/rockets/query';
static const dragons = '$spacexBaseUrl/v4/dragons/query';
static const roadster = '$spacexBaseUrl/v4/roadster/query';
static const ships = '$spacexBaseUrl/v4/ships/query';
// Launch URL
static const launches = '$spacexBaseUrl/v5/launches/query';
// SpaceX info URLs
static const companyInformation = '$spacexBaseUrl/v4/company';
static const companyAchievements = '$spacexBaseUrl/v4/history';
// Share details message
static const shareDetails = '#spacexGO';
// About page
static const authorProfile = 'https://twitter.com/jesusrp98';
static const authorPatreon = 'https://www.patreon.com/jesusrp98';
static const emailUrl =
'mailto:[email protected]?subject=About SpaceX GO!';
static const changelog =
'https://raw.githubusercontent.com/jesusrp98/spacex-go/master/CHANGELOG.md';
static const appSource = 'https://github.com/jesusrp98/spacex-go';
static const apiSource = 'https://github.com/r-spacex/SpaceX-API';
static const flutterPage = 'https://flutter.dev';
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/utils/translate.dart | import 'package:flutter/widgets.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
extension Translate on BuildContext {
String translate(
final String key, {
final Map<String, String> parameters,
}) {
try {
return FlutterI18n.translate(
this,
key,
translationParams: parameters,
);
} catch (_) {
return key;
}
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/tabs/launches.dart | import 'package:big_tip/big_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:search_page/search_page.dart';
import '../../../cubits/index.dart';
import '../../../models/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// Variable that determins the type of launches are shown within this view
enum LaunchType { upcoming, latest }
/// This tab holds information a specific type of launches,
/// upcoming or latest, defined by the model.
class LaunchesTab extends StatelessWidget {
final LaunchType type;
const LaunchesTab(this.type);
@override
Widget build(BuildContext context) {
return Scaffold(
body: RequestSliverPage<LaunchesCubit, List<List<Launch>>>(
title: context.translate(
type == LaunchType.upcoming
? 'spacex.upcoming.title'
: 'spacex.latest.title',
),
headerBuilder: (context, state, value) {
final launch = type == LaunchType.latest
? LaunchUtils.getLatestLaunch(value)
: null;
return SwiperHeader(
list: launch?.hasPhotos == true
? launch.photos
: SpaceXPhotos.upcoming,
);
},
popupMenu: Menu.home,
childrenBuilder: (context, state, value) {
final launches = value[type.index];
return [
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => LaunchCell(launches.elementAt(index)),
childCount: launches.length,
),
),
];
},
),
floatingActionButton: RequestBuilder<LaunchesCubit, List<List<Launch>>>(
onLoaded: (context, state, value) => FloatingActionButton(
heroTag: null,
tooltip: context.translate(
'spacex.other.tooltip.search',
),
onPressed: () => showSearch(
context: context,
delegate: SearchPage<Launch>(
items: LaunchUtils.getAllLaunches(value),
searchLabel: context.translate(
'spacex.other.tooltip.search',
),
suggestion: BigTip(
title: Text(
context.translate(
type == LaunchType.upcoming
? 'spacex.upcoming.title'
: 'spacex.latest.title',
),
style: Theme.of(context).textTheme.headline6.copyWith(
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
context.translate('spacex.search.suggestion.launch'),
style: Theme.of(context).textTheme.subtitle1.copyWith(
color: Theme.of(context).textTheme.caption.color,
),
),
child: Icon(Icons.search),
),
failure: BigTip(
title: Text(
context.translate(
type == LaunchType.upcoming
? 'spacex.upcoming.title'
: 'spacex.latest.title',
),
style: Theme.of(context).textTheme.headline6.copyWith(
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
context.translate('spacex.search.failure'),
style: Theme.of(context).textTheme.subtitle1.copyWith(
color: Theme.of(context).textTheme.caption.color,
),
),
child: Icon(Icons.sentiment_dissatisfied),
),
filter: (launch) => [
launch.rocket.name,
launch.name,
launch.flightNumber.toString(),
launch.year,
launch.launchpad.name,
launch.launchpad.fullName,
...launch.rocket.payloads.map((e) => e.customer),
...launch.rocket.cores.map((e) => e.landpad?.name),
...launch.rocket.cores.map((e) => e.landpad?.fullName),
...launch.rocket.cores.map(
(e) => e.getBlockData(context),
),
...launch.rocket.cores.map((e) => e.serial),
...launch.rocket.payloads.map((e) => e.capsule?.serial),
],
builder: (launch) => LaunchCell(launch),
),
),
child: Icon(Icons.search),
),
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/tabs/vehicles.dart | import 'package:big_tip/big_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:search_page/search_page.dart';
import '../../../cubits/index.dart';
import '../../../models/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// This tab holds information about all kind of SpaceX's vehicles,
/// such as rockets, capsules, Tesla Roadster & ships.
class VehiclesTab extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: RequestSliverPage<VehiclesCubit, List<Vehicle>>(
title: context.translate('spacex.vehicle.title'),
headerBuilder: (context, state, value) {
final photos = [
for (final vehicle in value) vehicle.getRandomPhoto()
];
return SwiperHeader(list: photos.sublist(0, 4));
},
popupMenu: Menu.home,
childrenBuilder: (context, state, value) => [
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => VehicleCell(value[index]),
childCount: value.length,
),
),
],
),
floatingActionButton: RequestBuilder<VehiclesCubit, List<Vehicle>>(
onLoaded: (context, state, value) => FloatingActionButton(
heroTag: null,
tooltip: context.translate(
'spacex.other.tooltip.search',
),
onPressed: () => showSearch(
context: context,
delegate: SearchPage<Vehicle>(
items: value,
searchLabel: context.translate(
'spacex.other.tooltip.search',
),
suggestion: BigTip(
title: Text(
context.translate(
'spacex.vehicle.title',
),
style: Theme.of(context).textTheme.headline6.copyWith(
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
context.translate(
'spacex.search.suggestion.vehicle',
),
style: Theme.of(context).textTheme.subtitle1.copyWith(
color: Theme.of(context).textTheme.caption.color,
),
),
child: Icon(Icons.search),
),
failure: BigTip(
title: Text(
context.translate(
'spacex.vehicle.title',
),
style: Theme.of(context).textTheme.headline6.copyWith(
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
context.translate(
'spacex.search.failure',
),
style: Theme.of(context).textTheme.subtitle1.copyWith(
color: Theme.of(context).textTheme.caption.color,
),
),
child: Icon(Icons.sentiment_dissatisfied),
),
filter: (vehicle) => [
vehicle.name,
vehicle.year,
vehicle.type,
],
builder: (vehicle) => VehicleCell(vehicle),
),
),
child: Icon(Icons.search),
),
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/tabs/index.dart | export 'company.dart';
export 'home.dart';
export 'launches.dart';
export 'vehicles.dart';
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/tabs/home.dart | import 'package:add_2_calendar/add_2_calendar.dart';
import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:row_collection/row_collection.dart';
import '../../../cubits/index.dart';
import '../../../models/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
import '../launches/index.dart';
/// This tab holds main information about the next launch.
/// It has a countdown widget.
class HomeTab extends StatefulWidget {
@override
_HomeTabState createState() => _HomeTabState();
}
class _HomeTabState extends State<HomeTab> {
ScrollController _controller;
double _offset = 0.0;
@override
void initState() {
super.initState();
_controller = ScrollController()
..addListener(() => setState(() => _offset = _controller.offset));
}
@override
Widget build(BuildContext context) {
return RequestSliverPage<LaunchesCubit, List<List<Launch>>>(
controller: _controller,
title: context.translate('spacex.home.title'),
popupMenu: Menu.home,
headerBuilder: (context, state, value) => _HeaderView(
launch: LaunchUtils.getUpcomingLaunch(value),
offset: _offset,
),
childrenBuilder: (context, state, value) => <Widget>[
SliverToBoxAdapter(
child: _HomeView(
LaunchUtils.getUpcomingLaunch(value),
),
),
],
);
}
}
class _HeaderView extends StatelessWidget {
final Launch launch;
final double offset;
const _HeaderView({
Key key,
this.launch,
this.offset,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final _sliverHeight =
MediaQuery.of(context).size.height * SliverBar.heightRatio;
final _isNotLandscape =
MediaQuery.of(context).orientation != Orientation.landscape;
return Stack(
alignment: Alignment.center,
children: <Widget>[
Opacity(
opacity: launch.isDateTooTentative && _isNotLandscape ? 1.0 : 0.64,
child: SwiperHeader(
list: List.from(SpaceXPhotos.home)..shuffle(),
),
),
if (_isNotLandscape)
AnimatedOpacity(
opacity: offset > _sliverHeight / 10 ? 0.0 : 1.0,
duration: Duration(milliseconds: 350),
child: launch.localLaunchDate.isAfter(DateTime.now()) &&
!launch.isDateTooTentative
? LaunchCountdown(launch.localLaunchDate)
: launch.hasVideo && !launch.isDateTooTentative
? InkWell(
onTap: () => context.openUrl(launch.getVideo),
child: Padding(
padding: EdgeInsets.only(right: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(
Icons.play_arrow,
color: Colors.white,
size: 50,
),
Separator.smallSpacer(),
Text(
context
.translate('spacex.home.tab.live_mission'),
textAlign: TextAlign.center,
style: GoogleFonts.robotoMono(
fontSize: 24,
color: Colors.white,
shadows: [
Shadow(
blurRadius: 4,
color: Theme.of(context).primaryColor,
),
],
),
),
],
),
),
)
: Separator.none(),
),
],
);
}
}
class _HomeView extends StatelessWidget {
final Launch launch;
const _HomeView(this.launch, {Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(children: <Widget>[
ListCell.icon(
icon: Icons.public,
title: context.translate(
'spacex.home.tab.mission.title',
parameters: {'rocket': launch.rocket.name},
),
subtitle: payloadSubtitle(context, launch.rocket.payloads),
onTap: () => Navigator.pushNamed(
context,
LaunchPage.route,
arguments: {'id': launch.id},
),
),
Separator.divider(indent: 72),
ListCell.icon(
icon: Icons.event,
title: context.translate(
'spacex.home.tab.date.title',
),
subtitle: launch.tentativeTime
? context.translate(
'spacex.home.tab.date.body_upcoming',
parameters: {'date': launch.getTentativeDate},
)
: context.translate(
'spacex.home.tab.date.body',
parameters: {
'date': launch.getTentativeDate,
'time': launch.getShortTentativeTime
},
),
onTap: !launch.tentativeTime
? () async {
await Add2Calendar.addEvent2Cal(Event(
title: launch.name,
description: launch.details ??
context.translate('spacex.launch.page.no_description'),
location: launch.launchpad.name ??
context.translate('spacex.other.unknown'),
startDate: launch.localLaunchDate,
endDate: launch.localLaunchDate.add(
Duration(minutes: 30),
),
));
}
: null,
),
Separator.divider(indent: 72),
ListCell.icon(
icon: Icons.location_on,
title: context.translate('spacex.home.tab.launchpad.title'),
subtitle: context.translate(
'spacex.home.tab.launchpad.body',
parameters: {'launchpad': launch.launchpad.name},
),
onTap: launch.launchpad != null
? () => Navigator.pushNamed(
context,
LaunchpadPage.route,
arguments: {'launchId': launch.id},
)
: null,
),
Separator.divider(indent: 72),
ListCell.icon(
icon: Icons.timer,
title: context.translate('spacex.home.tab.static_fire.title'),
subtitle: launch.staticFireDate == null
? context.translate('spacex.home.tab.static_fire.body_unknown')
: context.translate(
launch.staticFireDate.isBefore(DateTime.now())
? 'spacex.home.tab.static_fire.body_done'
: 'spacex.home.tab.static_fire.body',
parameters: {'date': launch.getStaticFireDate(context)},
),
),
Separator.divider(indent: 72),
if (launch.rocket.hasFairings)
ListCell.icon(
icon: Icons.directions_boat,
title: context.translate('spacex.home.tab.fairings.title'),
subtitle: fairingSubtitle(context, launch.rocket.fairings),
)
else
ListCell(
leading: SvgPicture.asset(
'assets/icons/capsule.svg',
colorBlendMode: BlendMode.srcATop,
width: 40,
height: 40,
color: Theme.of(context).brightness == Brightness.light
? Colors.black45
: null,
),
title: context.translate('spacex.home.tab.capsule.title'),
subtitle: capsuleSubtitle(context, launch.rocket.getSinglePayload),
onTap: launch.rocket.hasCapsule
? () => Navigator.pushNamed(
context,
CapsulePage.route,
arguments: {'launchId': launch.id},
)
: null,
),
Separator.divider(indent: 72),
AbsorbPointer(
absorbing: launch.rocket.isFirstStageNull,
child: ListCell(
leading: SvgPicture.asset(
'assets/icons/fins.svg',
colorBlendMode: BlendMode.srcATop,
width: 40,
height: 40,
color: Theme.of(context).brightness == Brightness.light
? Colors.black45
: null,
),
title: context.translate('spacex.home.tab.first_stage.title'),
subtitle: launch.rocket.isHeavy
? context.translate(
launch.rocket.isFirstStageNull
? 'spacex.home.tab.first_stage.body_null'
: 'spacex.home.tab.first_stage.heavy_dialog.body',
)
: coreSubtitle(
context: context,
core: launch.rocket.getSingleCore,
isSideCore:
launch.rocket.isSideCore(launch.rocket.getSingleCore),
),
onTap: !launch.rocket.isFirstStageNull
? () => launch.rocket.isHeavy
? showHeavyDialog(context, launch)
: openCorePage(
context: context,
launchId: launch.id,
coreId: launch.rocket.getSingleCore.id,
)
: null,
),
),
Separator.divider(indent: 72),
ListCell.icon(
icon: Icons.center_focus_weak,
title: context.translate('spacex.home.tab.landing.title'),
subtitle: landingSubtitle(context, launch.rocket.getSingleCore),
onTap: launch.rocket.getSingleCore.landpad != null
? () => Navigator.pushNamed(
context,
LandpadPage.route,
arguments: {
'launchId': launch.id,
'coreId': launch.rocket.getSingleCore.id,
},
)
: null,
),
Separator.divider(indent: 72)
]);
}
void openCorePage({BuildContext context, String launchId, String coreId}) {
Navigator.pushNamed(
context,
CorePage.route,
arguments: {
'launchId': launchId,
'coreId': coreId,
},
);
}
void showHeavyDialog(BuildContext context, Launch upcomingLaunch) =>
showBottomRoundDialog(
context: context,
title: context.translate(
'spacex.home.tab.first_stage.heavy_dialog.title',
),
padding: EdgeInsets.zero,
children: [
for (final core in upcomingLaunch.rocket.cores)
AbsorbPointer(
absorbing: core.id == null,
child: ListCell(
title: core.id != null
? context.translate(
'spacex.dialog.vehicle.title_core',
parameters: {'serial': core.serial},
)
: context.translate(
'spacex.home.tab.first_stage.heavy_dialog.core_null_title',
),
subtitle: coreSubtitle(
context: context,
core: core,
isSideCore: upcomingLaunch.rocket.isSideCore(core),
),
onTap: () => openCorePage(
context: context,
launchId: upcomingLaunch.id,
coreId: core.id,
),
contentPadding: EdgeInsets.symmetric(
horizontal: 20,
),
dense: true,
),
)
],
);
String landingSubtitle(BuildContext context, Core core) {
if (core.landingAttempt == null) {
return context.translate('spacex.home.tab.landing.body_null');
} else if (!core.landingAttempt) {
return context.translate('spacex.home.tab.landing.body_expended');
} else if (core.landpad == null && core.landingType != null) {
return context.translate(
'spacex.home.tab.landing.body_type',
parameters: {'type': core.landingType},
);
} else {
return context.translate(
'spacex.home.tab.landing.body',
parameters: {'zone': core.landpad.name},
);
}
}
String payloadSubtitle(BuildContext context, List<Payload> payloads) {
const maxPayload = 3;
final buffer = StringBuffer();
final payloadList = payloads.sublist(
0,
payloads.length > maxPayload ? maxPayload : payloads.length,
);
for (int i = 0; i < payloads.length; ++i) {
buffer.write(
context.translate(
'spacex.home.tab.mission.body_payload',
parameters: {
'name': payloads[i].name,
'orbit': payloads[i].orbit
},
) +
(i + 1 == payloadList.length ? '' : ', '),
);
}
return context.translate(
'spacex.home.tab.mission.body',
parameters: {'payloads': buffer.toString()},
);
}
String fairingSubtitle(BuildContext context, FairingsDetails fairing) =>
fairing.reused == null && fairing.recoveryAttempt == null
? context.translate('spacex.home.tab.fairings.body_null')
: fairing.reused != null && fairing.recoveryAttempt == null
? context.translate(
fairing.reused == true
? 'spacex.home.tab.fairings.body_reused'
: 'spacex.home.tab.fairings.body_new',
)
: context.translate(
'spacex.home.tab.fairings.body',
parameters: {
'reused': context.translate(
fairing.reused == true
? 'spacex.home.tab.fairings.body_reused'
: 'spacex.home.tab.fairings.body_new',
),
'catched': context.translate(
fairing.recoveryAttempt == true
? 'spacex.home.tab.fairings.body_catching'
: 'spacex.home.tab.fairings.body_dispensed',
)
},
);
String coreSubtitle({BuildContext context, Core core, bool isSideCore}) =>
core.id == null || core.reused == null
? context.translate('spacex.home.tab.first_stage.body_null')
: context.translate(
'spacex.home.tab.first_stage.body',
parameters: {
'booster': context.translate(
isSideCore
? 'spacex.home.tab.first_stage.side_core'
: 'spacex.home.tab.first_stage.booster',
),
'reused': context.translate(
core.reused
? 'spacex.home.tab.first_stage.body_reused'
: 'spacex.home.tab.first_stage.body_new',
),
},
);
String capsuleSubtitle(BuildContext context, Payload payload) =>
payload.capsule?.serial == null
? context.translate('spacex.home.tab.capsule.body_null')
: context.translate(
'spacex.home.tab.capsule.body',
parameters: {
'reused': payload.reused
? context.translate(
'spacex.home.tab.capsule.body_reused',
)
: context.translate(
'spacex.home.tab.capsule.body_new',
)
},
);
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/tabs/company.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import '../../../cubits/index.dart';
import '../../../models/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// This tab holds information about SpaceX-as-a-company,
/// such as various numbers & achievements.
class CompanyTab extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SliverPage(
title: context.translate('spacex.company.title'),
header: SwiperHeader(list: List.from(SpaceXPhotos.company)..shuffle()),
popupMenu: Menu.home,
children: [
_ComapnyInfoView(),
_AchievementsListView(),
],
);
}
}
class _ComapnyInfoView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RequestBuilder<CompanyCubit, CompanyInfo>(
onLoading: (context, state, value) => LoadingSliverView(),
onLoaded: (context, state, value) => SliverToBoxAdapter(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SafeArea(
top: false,
minimum: const EdgeInsets.only(left: 16, right: 16, top: 16),
child: RowLayout(
children: <Widget>[
RowLayout(
space: 6,
children: <Widget>[
Text(
value.fullName,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.subtitle1,
),
Text(
value.getFounderDate(context),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.subtitle1.copyWith(
color: Theme.of(context).textTheme.caption.color,
),
),
],
),
RowItem.text(
context.translate('spacex.company.tab.ceo'),
value.ceo,
),
RowItem.text(
context.translate('spacex.company.tab.cto'),
value.cto,
),
RowItem.text(
context.translate('spacex.company.tab.coo'),
value.coo,
),
RowItem.text(
context.translate('spacex.company.tab.valuation'),
value.getValuation,
),
RowItem.text(
context.translate('spacex.company.tab.location'),
value.getLocation,
),
RowItem.text(
context.translate('spacex.company.tab.employees'),
value.getEmployees,
),
ExpandText(value.details),
],
),
),
],
),
),
);
}
}
class _AchievementsListView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RequestBuilder<AchievementsCubit, List<Achievement>>(
onLoading: (context, state, vale) => LoadingSliverView(),
onLoaded: (context, state, value) => SliverToBoxAdapter(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
HeaderText(
context.translate('spacex.company.tab.achievements'),
head: true,
),
ListView.builder(
padding: EdgeInsets.zero,
shrinkWrap: true,
primary: false,
itemBuilder: (context, index) => AchievementCell(
achievement: value[index],
index: index,
),
itemCount: value.length,
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/launches/capsule.dart | import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:provider/provider.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import '../../../cubits/index.dart';
import '../../../utils/photos.dart';
import '../../widgets/index.dart';
import 'index.dart';
/// This view displays information about a specific capsule,
/// used in a NASA mission.
class CapsulePage extends StatelessWidget {
final String launchId;
const CapsulePage({Key key, this.launchId}) : super(key: key);
static const route = '/capsule';
@override
Widget build(BuildContext context) {
final capsule = context
.watch<LaunchesCubit>()
.getLaunch(launchId)
.rocket
.getSinglePayload
.capsule;
return Scaffold(
body: SliverPage(
title: FlutterI18n.translate(
context,
'spacex.dialog.vehicle.title_capsule',
translationParams: {'serial': capsule.serial},
),
header: SwiperHeader(list: List.from(SpaceXPhotos.capsules)..shuffle()),
children: <Widget>[
SliverSafeArea(
top: false,
sliver: SliverToBoxAdapter(
child: RowLayout.body(children: <Widget>[
RowItem.text(
FlutterI18n.translate(
context,
'spacex.dialog.vehicle.model',
),
capsule.type,
),
RowItem.text(
FlutterI18n.translate(
context,
'spacex.dialog.vehicle.status',
),
capsule.getStatus,
),
RowItem.text(
FlutterI18n.translate(
context,
'spacex.dialog.vehicle.first_launched',
),
capsule.getFirstLaunched(context),
),
RowItem.text(
FlutterI18n.translate(
context,
'spacex.dialog.vehicle.launches',
),
capsule.getLaunches,
),
RowItem.text(
FlutterI18n.translate(
context,
'spacex.dialog.vehicle.splashings',
),
capsule.getSplashings,
),
Separator.divider(),
if (capsule.hasMissions) ...[
for (final launch in capsule.launches)
RowTap(
FlutterI18n.translate(
context,
'spacex.dialog.vehicle.mission',
translationParams: {
'number': launch.flightNumber.toString()
},
),
launch.name,
onTap: () => Navigator.pushNamed(
context,
LaunchPage.route,
arguments: {'id': launch.id},
),
),
Separator.divider()
],
ExpandText(capsule.getDetails(context))
]),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/launches/launchpad.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import '../../../cubits/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// This view displays information about a specific launchpad,
/// where rockets get rocketed to the sky...
class LaunchpadPage extends StatelessWidget {
final String launchId;
const LaunchpadPage({Key key, this.launchId}) : super(key: key);
static const route = '/launchpad';
@override
Widget build(BuildContext context) {
final launchpad =
context.watch<LaunchesCubit>().getLaunch(launchId).launchpad;
return Scaffold(
body: SliverPage(
title: launchpad.name,
header: CacheImage(launchpad.imageUrl),
children: <Widget>[
SliverSafeArea(
top: false,
sliver: SliverToBoxAdapter(
child: RowLayout.body(children: <Widget>[
Text(
launchpad.fullName,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.subtitle1,
),
RowItem.text(
context.translate('spacex.dialog.pad.status'),
launchpad.getStatus,
),
RowItem.text(
context.translate('spacex.dialog.pad.location'),
launchpad.locality,
),
RowItem.text(
context.translate('spacex.dialog.pad.state'),
launchpad.region,
),
RowItem.text(
context.translate('spacex.dialog.pad.coordinates'),
launchpad.getCoordinates,
),
RowItem.text(
context.translate('spacex.dialog.pad.launches_successful'),
launchpad.getSuccessfulLaunches,
),
Separator.divider(),
ExpandText(launchpad.details)
]),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/launches/landpad.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import '../../../cubits/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// This view displays information about a specific landpad,
/// where rockets now land.
class LandpadPage extends StatelessWidget {
final String launchId;
final String coreId;
const LandpadPage({
Key key,
this.launchId,
this.coreId,
}) : super(key: key);
static const route = '/landpad';
@override
Widget build(BuildContext context) {
final landpad = context
.watch<LaunchesCubit>()
.getLaunch(launchId)
.rocket
.getCore(coreId)
.landpad;
return Scaffold(
body: SliverPage(
title: landpad.name,
header: CacheImage(landpad.imageUrl),
children: <Widget>[
SliverSafeArea(
top: false,
sliver: SliverToBoxAdapter(
child: RowLayout.body(children: <Widget>[
Text(
landpad.fullName,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.subtitle1,
),
RowItem.text(
context.translate('spacex.dialog.pad.status'),
landpad.getStatus,
),
RowItem.text(context.translate('spacex.dialog.pad.location'),
landpad.locality),
RowItem.text(
context.translate('spacex.dialog.pad.state'),
landpad.region,
),
RowItem.text(
context.translate('spacex.dialog.pad.coordinates'),
landpad.getCoordinates,
),
RowItem.text(
context.translate('spacex.dialog.pad.landing_type'),
landpad.type,
),
RowItem.text(
context.translate('spacex.dialog.pad.landings_successful'),
landpad.getSuccessfulLandings,
),
Separator.divider(),
ExpandText(landpad.details)
]),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/launches/launch.dart | import 'package:add_2_calendar/add_2_calendar.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cherry_components/cherry_components.dart';
import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import 'package:share_plus/share_plus.dart';
import 'package:sliver_fab/sliver_fab.dart';
import '../../../cubits/index.dart';
import '../../../models/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
import '../vehicles/index.dart';
import 'index.dart';
/// This view displays all information about a specific launch.
class LaunchPage extends StatelessWidget {
final String id;
const LaunchPage(this.id);
static const route = '/launch';
@override
Widget build(BuildContext context) {
final _launch = context.watch<LaunchesCubit>().getLaunch(id);
return Scaffold(
body: SliverFab(
expandedHeight: MediaQuery.of(context).size.height * 0.3,
floatingWidget: !_launch.tentativeTime
? SafeArea(
top: false,
bottom: false,
left: false,
child: _launch.hasVideo
? FloatingActionButton(
heroTag: null,
tooltip: context.translate(
'spacex.other.tooltip.watch_replay',
),
onPressed: () => context.openUrl(_launch.getVideo),
child: Icon(Icons.ondemand_video),
)
: FloatingActionButton(
heroTag: null,
backgroundColor: Theme.of(context).accentColor,
tooltip: context.translate(
'spacex.other.tooltip.add_event',
),
onPressed: () async {
await Add2Calendar.addEvent2Cal(Event(
title: _launch.name,
description: _launch.details ??
context.translate(
'spacex.launch.page.no_description',
),
location: _launch.launchpad.name ??
context.translate('spacex.other.unknown'),
startDate: _launch.localLaunchDate,
endDate: _launch.localLaunchDate.add(
Duration(minutes: 30),
),
));
},
child: Icon(Icons.event),
),
)
: Separator.none(),
slivers: <Widget>[
SliverBar(
title: _launch.name,
header: SwiperHeader(
list: _launch.hasPhotos
? _launch.photos
: List.from(SpaceXPhotos.upcoming)
..shuffle(),
),
actions: <Widget>[
IconButton(
icon: IconShadow(Icons.adaptive.share),
onPressed: () => Share.share(
context.translate(
_launch.localLaunchDate.isAfter(DateTime.now())
? 'spacex.other.share.launch.future'
: 'spacex.other.share.launch.past',
parameters: {
'number': _launch.flightNumber.toString(),
'name': _launch.name,
'launchpad': _launch.launchpad.name ??
context.translate('spacex.other.unknown'),
'date': _launch.getTentativeDate,
'details': Url.shareDetails
},
),
),
tooltip: context.translate('spacex.other.menu.share'),
),
],
menuItemBuilder: (context) => [
for (final url in Menu.launch)
PopupMenuItem(
value: url,
enabled: _launch.isUrlEnabled(url),
child: Text(context.translate(url)),
)
],
onMenuItemSelected: (name) => context.openUrl(_launch.getUrl(name)),
),
SliverSafeArea(
top: false,
sliver: SliverToBoxAdapter(
child: RowLayout.cards(children: <Widget>[
_missionCard(context),
_firstStageCard(context),
_secondStageCard(context),
]),
),
),
],
),
);
}
Widget _missionCard(BuildContext context) {
final _launch = context.watch<LaunchesCubit>().getLaunch(id);
return CardCell.header(
context,
leading: AbsorbPointer(
absorbing: !_launch.hasPatch,
child: ProfileImage.big(
_launch.patchUrl,
onTap: () => context.openUrl(_launch.patchUrl),
),
),
title: _launch.name,
subtitle: [
ItemCell(
icon: Icons.calendar_today,
text: _launch.getLaunchDate(context),
),
ItemCell(
icon: Icons.location_on,
text: _launch.launchpad.name ??
context.translate('spacex.other.unknown'),
onTap: _launch.launchpad.name == null
? null
: () => Navigator.pushNamed(
context,
LaunchpadPage.route,
arguments: {'launchId': id},
),
),
],
details: _launch.getDetails(context),
);
}
Widget _firstStageCard(BuildContext context) {
final _launch = context.watch<LaunchesCubit>().getLaunch(id);
return CardCell.body(
context,
title: context.translate('spacex.launch.page.rocket.title'),
child: RowLayout(children: <Widget>[
RowTap(
context.translate('spacex.launch.page.rocket.model'),
_launch.rocket.name,
onTap: () => Navigator.pushNamed(
context,
VehiclePage.route,
arguments: {
'id': _launch.rocket.id,
},
),
),
if (_launch.avoidedStaticFire)
RowItem.boolean(
context.translate('spacex.launch.page.rocket.static_fire_date'),
false,
)
else
RowItem.text(
context.translate('spacex.launch.page.rocket.static_fire_date'),
_launch.getStaticFireDate(context),
),
RowItem.text(
context.translate('spacex.launch.page.rocket.launch_window'),
_launch.getLaunchWindow(context),
),
if (!_launch.upcoming)
RowItem.boolean(
context.translate('spacex.launch.page.rocket.launch_success'),
_launch.success,
),
if (_launch.success == false) ...<Widget>[
Separator.divider(),
RowItem.text(
context.translate('spacex.launch.page.rocket.failure.time'),
_launch.failure.getTime,
),
RowItem.text(
context.translate('spacex.launch.page.rocket.failure.altitude'),
_launch.failure.getAltitude(context),
),
ExpandText(_launch.failure.getReason)
],
for (final core in _launch.rocket.cores)
_getCores(
context,
core,
isUpcoming: _launch.upcoming,
),
]),
);
}
Widget _secondStageCard(BuildContext context) {
final _launch = context.watch<LaunchesCubit>().getLaunch(id);
final _fairings = _launch.rocket.fairings;
return CardCell.body(
context,
title: context.translate('spacex.launch.page.payload.title'),
child: RowLayout(children: <Widget>[
if (_launch.rocket.hasFairings) ...<Widget>[
RowItem.boolean(
context.translate('spacex.launch.page.payload.fairings.reused'),
_fairings.reused,
),
if (_fairings.recoveryAttempt == true)
RowItem.boolean(
context.translate(
'spacex.launch.page.payload.fairings.recovery_success',
),
_fairings.recovered,
)
else
RowItem.boolean(
context.translate(
'spacex.launch.page.payload.fairings.recovery_attempt',
),
_fairings.recoveryAttempt,
),
],
if (_fairings != null) Separator.divider(),
_getPayload(context, _launch.rocket.getSinglePayload),
if (_launch.rocket.hasMultiplePayload)
ExpandList(
hint: context.translate('spacex.other.all_payload'),
child: Column(children: <Widget>[
for (final payload in _launch.rocket.payloads.sublist(1)) ...[
Separator.divider(),
Separator.spacer(),
_getPayload(context, payload),
if (_launch.rocket.payloads.indexOf(payload) !=
_launch.rocket.payloads.length - 1)
Separator.spacer(),
]
]),
)
]),
);
}
Widget _getCores(BuildContext context, Core core, {bool isUpcoming = false}) {
return RowLayout(children: <Widget>[
Separator.divider(),
RowTap(
context.translate('spacex.launch.page.rocket.core.serial'),
core.serial,
onTap: () => Navigator.pushNamed(
context,
CorePage.route,
arguments: {
'launchId': id,
'coreId': core.id,
},
),
),
RowItem.text(
context.translate('spacex.launch.page.rocket.core.model'),
core.getBlock(context),
),
RowItem.boolean(
context.translate('spacex.launch.page.rocket.core.reused'),
core.reused,
),
if (core.landingAttempt == true) ...<Widget>[
RowTap(
context.translate('spacex.launch.page.rocket.core.landing_zone'),
core.landpad?.name,
onTap: () => Navigator.pushNamed(
context,
LandpadPage.route,
arguments: {
'launchId': id,
'coreId': core.id,
},
),
),
if (!isUpcoming)
RowItem.boolean(
context.translate('spacex.launch.page.rocket.core.landing_success'),
core.landingSuccess,
)
] else
RowItem.boolean(
context.translate('spacex.launch.page.rocket.core.landing_attempt'),
core.landingAttempt,
),
if (core.landingAttempt == true)
ExpandChild(
child: RowLayout(children: <Widget>[
RowItem.boolean(
context.translate('spacex.launch.page.rocket.core.landing_legs'),
core.hasLegs,
),
RowItem.boolean(
context.translate('spacex.launch.page.rocket.core.gridfins'),
core.hasGridfins,
),
]),
),
]);
}
Widget _getPayload(BuildContext context, Payload payload) {
return RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.launch.page.payload.name'),
payload.getName(context),
),
if (payload.isNasaPayload) ...<Widget>[
RowTap(
context.translate('spacex.launch.page.payload.capsule_serial'),
payload.capsule?.serial,
onTap: () => Navigator.pushNamed(
context,
CapsulePage.route,
arguments: {
'launchId': id,
},
),
),
RowItem.boolean(
context.translate('spacex.launch.page.payload.capsule_reused'),
payload.reused,
),
],
RowItem.text(
context.translate('spacex.launch.page.payload.manufacturer'),
payload.getManufacturer(context),
),
RowItem.text(
context.translate('spacex.launch.page.payload.customer'),
payload.getCustomer(context),
),
RowItem.text(
context.translate('spacex.launch.page.payload.nationality'),
payload.getNationality(context),
),
RowItem.text(
context.translate('spacex.launch.page.payload.mass'),
payload.getMass(context),
),
RowItem.text(
context.translate('spacex.launch.page.payload.orbit'),
payload.getOrbit(context),
),
ExpandChild(
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.launch.page.payload.periapsis'),
payload.getPeriapsis(context),
),
RowItem.text(
context.translate('spacex.launch.page.payload.apoapsis'),
payload.getApoapsis(context),
),
RowItem.text(
context.translate('spacex.launch.page.payload.inclination'),
payload.getInclination(context),
),
RowItem.text(
context.translate('spacex.launch.page.payload.period'),
payload.getPeriod(context),
),
]),
)
]);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/launches/core.dart | import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import '../../../cubits/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
import 'index.dart';
/// This view displays information about a specific core,
/// used in a mission.
class CorePage extends StatelessWidget {
final String launchId;
final String coreId;
const CorePage({
Key key,
this.launchId,
this.coreId,
}) : super(key: key);
static const route = '/core';
@override
Widget build(BuildContext context) {
final core = context
.watch<LaunchesCubit>()
.getLaunch(launchId)
.rocket
.getCore(coreId);
return Scaffold(
body: SliverPage(
title: context.translate(
'spacex.dialog.vehicle.title_core',
parameters: {'serial': core.serial},
),
header: SwiperHeader(list: List.from(SpaceXPhotos.cores)..shuffle()),
children: <Widget>[
SliverSafeArea(
top: false,
sliver: SliverToBoxAdapter(
child: RowLayout.body(children: <Widget>[
RowItem.text(
context.translate('spacex.dialog.vehicle.model'),
core.getBlock(context),
),
RowItem.text(
context.translate('spacex.dialog.vehicle.status'),
core.getStatus,
),
RowItem.text(
context.translate('spacex.dialog.vehicle.first_launched'),
core.getFirstLaunched(context),
),
RowItem.text(
context.translate('spacex.dialog.vehicle.launches'),
core.getLaunches,
),
RowItem.text(
context.translate('spacex.dialog.vehicle.landings_rtls'),
core.getRtlsLandings,
),
RowItem.text(
context.translate('spacex.dialog.vehicle.landings_asds'),
core.getAsdsLandings,
),
Separator.divider(),
if (core.hasMissions) ...[
for (final mission in core.launches)
RowTap(
context.translate(
'spacex.dialog.vehicle.mission',
parameters: {'number': mission.flightNumber.toString()},
),
mission.name,
onTap: () => Navigator.pushNamed(
context,
LaunchPage.route,
arguments: {'id': mission.id},
),
),
Separator.divider()
],
ExpandText(core.getDetails(context))
]),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/launches/index.dart | export 'capsule.dart';
export 'core.dart';
export 'index.dart';
export 'landpad.dart';
export 'launch.dart';
export 'launchpad.dart';
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/vehicles/roadster.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import 'package:share_plus/share_plus.dart';
import 'package:sliver_fab/sliver_fab.dart';
import '../../../cubits/index.dart';
import '../../../models/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// Displays live information about Elon Musk's Tesla Roadster.
class RoadsterPage extends StatelessWidget {
final String id;
const RoadsterPage(this.id, {Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final RoadsterVehicle _roadster =
context.watch<VehiclesCubit>().getVehicle(id);
return Scaffold(
body: SliverFab(
floatingWidget: SafeArea(
top: false,
bottom: false,
left: false,
child: FloatingActionButton(
heroTag: null,
tooltip: context.translate('spacex.other.tooltip.watch_replay'),
onPressed: () => context.openUrl(_roadster.url),
child: Icon(Icons.ondemand_video),
),
),
expandedHeight: MediaQuery.of(context).size.height * 0.3,
slivers: <Widget>[
SliverBar(
title: _roadster.name,
header: SwiperHeader(
list: _roadster.photos,
builder: (_, index) => CacheImage(_roadster.getPhoto(index)),
),
actions: <Widget>[
IconButton(
icon: IconShadow(Icons.adaptive.share),
onPressed: () => Share.share(
context.translate(
'spacex.other.share.roadster',
parameters: {
'date': _roadster.getLaunchDate(context),
'speed': _roadster.getSpeed,
'earth_distance': _roadster.getEarthDistance,
'details': Url.shareDetails
},
),
),
tooltip: context.translate('spacex.other.menu.share'),
),
],
menuItemBuilder: (context) => [
for (final item in Menu.wikipedia)
PopupMenuItem(
value: item,
child: Text(context.translate(item)),
)
],
onMenuItemSelected: (text) => context.openUrl(_roadster.url),
),
SliverSafeArea(
top: false,
sliver: SliverToBoxAdapter(
child: RowLayout.cards(children: <Widget>[
_roadsterCard(context),
_vehicleCard(context),
_orbitCard(context),
ItemCell(
icon: Icons.refresh,
text: context.translate(
'spacex.vehicle.roadster.data_updated',
),
),
]),
),
),
],
),
);
}
Widget _roadsterCard(BuildContext context) {
final RoadsterVehicle _roadster =
context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.roadster.description.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.vehicle.roadster.description.launch_date'),
_roadster.getFullFirstFlight,
),
RowItem.text(
context.translate(
'spacex.vehicle.roadster.description.launch_vehicle',
),
'Falcon Heavy',
),
Separator.divider(),
ExpandText(_roadster.description)
]),
);
}
Widget _vehicleCard(BuildContext context) {
final RoadsterVehicle _roadster =
context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.roadster.vehicle.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.vehicle.roadster.vehicle.mass'),
_roadster.getMass(context),
),
RowItem.text(
context.translate('spacex.vehicle.roadster.vehicle.speed'),
_roadster.getSpeed,
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.roadster.vehicle.distance_earth'),
_roadster.getEarthDistance,
),
RowItem.text(
context.translate('spacex.vehicle.roadster.vehicle.distance_mars'),
_roadster.getMarsDistance,
),
]),
);
}
Widget _orbitCard(BuildContext context) {
final RoadsterVehicle _roadster =
context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.roadster.orbit.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.vehicle.roadster.orbit.type'),
_roadster.getOrbit,
),
RowItem.text(
context.translate('spacex.vehicle.roadster.orbit.period'),
_roadster.getPeriod(context),
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.roadster.orbit.inclination'),
_roadster.getInclination,
),
RowItem.text(
context.translate('spacex.vehicle.roadster.orbit.longitude'),
_roadster.getLongitude,
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.roadster.orbit.apoapsis'),
_roadster.getApoapsis,
),
RowItem.text(
context.translate('spacex.vehicle.roadster.orbit.periapsis'),
_roadster.getPeriapsis,
),
]),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/vehicles/ship.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import 'package:share_plus/share_plus.dart';
import '../../../cubits/index.dart';
import '../../../models/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
import '../launches/index.dart';
/// This view all information about a specific ship. It displays Ship's specs.
class ShipPage extends StatelessWidget {
final String id;
const ShipPage(this.id);
@override
Widget build(BuildContext context) {
final ShipVehicle _ship = context.watch<VehiclesCubit>().getVehicle(id);
return Scaffold(
body: CustomScrollView(slivers: <Widget>[
SliverBar(
title: _ship.name,
header: InkWell(
onTap: () => context.openUrl(_ship.getProfilePhoto),
child: CacheImage(_ship?.getProfilePhoto),
),
actions: <Widget>[
IconButton(
icon: IconShadow(Icons.adaptive.share),
onPressed: () => Share.share(
context.translate(
'spacex.other.share.ship.body',
parameters: {
'date': _ship.getBuiltFullDate,
'name': _ship.name,
'role': _ship.primaryRole,
'port': _ship.homePort,
'missions': _ship.hasMissions
? context.translate(
'spacex.other.share.ship.missions',
parameters: {
'missions': _ship.missions.length.toString()
},
)
: context
.translate('spacex.other.share.ship.any_missions'),
'details': Url.shareDetails
},
),
),
tooltip: context.translate('spacex.other.menu.share'),
),
],
menuItemBuilder: (context) => [
for (final item in Menu.ship)
PopupMenuItem(
value: item,
child: Text(context.translate(item)),
)
],
onMenuItemSelected: (text) => context.openUrl(_ship.url),
),
SliverSafeArea(
top: false,
sliver: SliverToBoxAdapter(
child: RowLayout.cards(children: <Widget>[
_shipCard(context),
_specsCard(context),
_missionsCard(context),
]),
),
),
]),
);
}
Widget _shipCard(BuildContext context) {
final ShipVehicle _ship = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.ship.description.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.vehicle.ship.description.home_port'),
_ship.homePort),
RowItem.text(
context.translate('spacex.vehicle.ship.description.built_date'),
_ship.getBuiltFullDate,
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.ship.specifications.feature'),
_ship.use,
),
RowItem.text(
context.translate('spacex.vehicle.ship.specifications.model'),
_ship.getModel(context),
),
]),
);
}
Widget _specsCard(BuildContext context) {
final ShipVehicle _ship = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.ship.specifications.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.vehicle.ship.specifications.role_primary'),
_ship.primaryRole,
),
if (_ship.hasSeveralRoles)
RowItem.text(
context.translate(
'spacex.vehicle.ship.specifications.role_secondary',
),
_ship.secondaryRole,
),
RowItem.text(
context.translate('spacex.vehicle.ship.specifications.status'),
_ship.getStatus(context),
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.ship.specifications.mass'),
_ship.getMass(context),
),
RowItem.text(
context.translate('spacex.vehicle.ship.specifications.speed'),
_ship.getSpeed(context),
),
]),
);
}
Widget _missionsCard(BuildContext context) {
final ShipVehicle _ship = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.ship.missions.title'),
child: _ship.hasMissions
? RowLayout(
children: <Widget>[
if (_ship.missions.length > 5) ...[
for (final mission in _ship.missions.sublist(0, 5))
RowTap(
context.translate(
'spacex.vehicle.ship.missions.mission',
parameters: {'number': mission.flightNumber.toString()},
),
mission.name,
onTap: () => Navigator.pushNamed(
context,
LaunchPage.route,
arguments: {'id': mission.id},
),
),
ExpandChild(
child: RowLayout(
children: <Widget>[
for (final mission in _ship.missions.sublist(5))
RowTap(
context.translate(
'spacex.vehicle.ship.missions.mission',
parameters: {
'number': mission.flightNumber.toString()
},
),
mission.name,
onTap: () => Navigator.pushNamed(
context,
LaunchPage.route,
arguments: {'id': mission.id},
),
),
],
),
)
] else
for (final mission in _ship.missions)
RowTap(
context.translate(
'spacex.vehicle.ship.missions.mission',
parameters: {'number': mission.flightNumber.toString()},
),
mission.name,
onTap: () => Navigator.pushNamed(
context,
LaunchPage.route,
arguments: {'id': mission.id},
),
),
],
)
: Text(
context.translate('spacex.vehicle.ship.missions.no_missions'),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 15,
color: Theme.of(context).textTheme.caption.color,
),
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/vehicles/index.dart | export 'dragon.dart';
export 'index.dart';
export 'roadster.dart';
export 'rocket.dart';
export 'ship.dart';
export 'vehicle.dart';
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/vehicles/dragon.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import 'package:share_plus/share_plus.dart';
import '../../../cubits/index.dart';
import '../../../models/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// This view all information about a Dragon capsule model. It displays CapsuleInfo's specs.
class DragonPage extends StatelessWidget {
final String id;
const DragonPage(this.id);
@override
Widget build(BuildContext context) {
final DragonVehicle _dragon = context.watch<VehiclesCubit>().getVehicle(id);
return Scaffold(
body: CustomScrollView(slivers: <Widget>[
SliverBar(
title: _dragon.name,
header: SwiperHeader(
list: _dragon.photos,
builder: (_, index) => CacheImage(_dragon.getPhoto(index)),
),
actions: <Widget>[
IconButton(
icon: IconShadow(Icons.adaptive.share),
onPressed: () => Share.share(
context.translate(
'spacex.other.share.capsule.body',
parameters: {
'name': _dragon.name,
'launch_payload': _dragon.getLaunchMass,
'return_payload': _dragon.getReturnMass,
'people': _dragon.isCrewEnabled
? context.translate(
'spacex.other.share.capsule.people',
parameters: {'people': _dragon.crew.toString()},
)
: context
.translate('spacex.other.share.capsule.no_people'),
'details': Url.shareDetails
},
),
),
tooltip: context.translate('spacex.other.menu.share'),
),
],
menuItemBuilder: (context) => [
for (final item in Menu.wikipedia)
PopupMenuItem(
value: item,
child: Text(context.translate(item)),
)
],
onMenuItemSelected: (text) => context.openUrl(_dragon.url),
),
SliverSafeArea(
top: false,
sliver: SliverToBoxAdapter(
child: RowLayout.cards(children: <Widget>[
_capsuleCard(context),
_specsCard(context),
_thrustersCard(context),
]),
),
),
]),
);
}
Widget _capsuleCard(BuildContext context) {
final DragonVehicle _dragon = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.capsule.description.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.vehicle.capsule.description.launch_maiden'),
_dragon.getFullFirstFlight,
),
RowItem.text(
context.translate('spacex.vehicle.capsule.description.crew_capacity'),
_dragon.getCrew(context),
),
RowItem.boolean(
context.translate('spacex.vehicle.capsule.description.active'),
_dragon.active,
),
Separator.divider(),
ExpandText(_dragon.description)
]),
);
}
Widget _specsCard(BuildContext context) {
final DragonVehicle _dragon = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.capsule.specifications.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate(
'spacex.vehicle.capsule.specifications.payload_launch',
),
_dragon.getLaunchMass,
),
RowItem.text(
context.translate(
'spacex.vehicle.capsule.specifications.payload_return',
),
_dragon.getReturnMass,
),
RowItem.boolean(
context.translate('spacex.vehicle.capsule.description.reusable'),
_dragon.reusable,
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.capsule.specifications.height'),
_dragon.getHeight,
),
RowItem.text(
context.translate('spacex.vehicle.capsule.specifications.diameter'),
_dragon.getDiameter,
),
RowItem.text(
context.translate('spacex.vehicle.capsule.specifications.mass'),
_dragon.getMass(context),
),
]),
);
}
Widget _thrustersCard(BuildContext context) {
final DragonVehicle _dragon = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.capsule.thruster.title'),
child: RowLayout(children: <Widget>[
for (final thruster in _dragon.thrusters)
_getThruster(
context: context,
thruster: thruster,
isFirst: _dragon.thrusters.first == thruster,
),
]),
);
}
Widget _getThruster({BuildContext context, Thruster thruster, bool isFirst}) {
return RowLayout(children: <Widget>[
if (!isFirst) Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.capsule.thruster.model'),
thruster.model,
),
RowItem.text(
context.translate('spacex.vehicle.capsule.thruster.amount'),
thruster.getAmount,
),
RowItem.text(
context.translate('spacex.vehicle.capsule.thruster.fuel'),
thruster.getFuel,
),
RowItem.text(
context.translate('spacex.vehicle.capsule.thruster.oxidizer'),
thruster.getOxidizer,
),
RowItem.text(
context.translate('spacex.vehicle.capsule.thruster.thrust'),
thruster.getThrust,
),
RowItem.text(
context.translate('spacex.vehicle.capsule.thruster.isp'),
thruster.getIsp,
),
]);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/vehicles/rocket.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:row_collection/row_collection.dart';
import 'package:row_item/row_item.dart';
import 'package:share_plus/share_plus.dart';
import '../../../cubits/index.dart';
import '../../../models/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// This view all information about a Falcon rocket model. It displays RocketInfo's specs.
class RocketPage extends StatelessWidget {
final String id;
const RocketPage(this.id);
@override
Widget build(BuildContext context) {
final RocketVehicle _rocket = context.watch<VehiclesCubit>().getVehicle(id);
return Scaffold(
body: CustomScrollView(slivers: <Widget>[
SliverBar(
title: _rocket.name,
header: SwiperHeader(
list: _rocket.photos,
builder: (_, index) => CacheImage(_rocket.getPhoto(index)),
),
actions: <Widget>[
IconButton(
icon: IconShadow(Icons.adaptive.share),
onPressed: () => Share.share(
context.translate(
'spacex.other.share.rocket',
parameters: {
'name': _rocket.name,
'height': _rocket.getHeight,
'engines': _rocket.firstStage.engines.toString(),
'type': _rocket.engine.getName,
'thrust': _rocket.firstStage.getThrust,
'payload': _rocket.payloadWeights[0].getMass,
'orbit': _rocket.payloadWeights[0].name,
'details': Url.shareDetails
},
),
),
tooltip: context.translate('spacex.other.menu.share'),
),
],
menuItemBuilder: (context) => [
for (final item in Menu.wikipedia)
PopupMenuItem(
value: item,
child: Text(context.translate(item)),
)
],
onMenuItemSelected: (text) => context.openUrl(_rocket.url),
),
SliverSafeArea(
top: false,
sliver: SliverToBoxAdapter(
child: RowLayout.cards(children: <Widget>[
_rocketCard(context),
_specsCard(context),
_payloadsCard(context),
_stages(context),
_enginesCard(context),
]),
),
),
]),
);
}
Widget _rocketCard(BuildContext context) {
final RocketVehicle _rocket = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.rocket.description.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.vehicle.rocket.description.launch_maiden'),
_rocket.getFullFirstFlight,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.description.launch_cost'),
_rocket.getLaunchCost,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.description.success_rate'),
_rocket.getSuccessRate(context),
),
RowItem.boolean(
context.translate('spacex.vehicle.rocket.description.active'),
_rocket.active,
),
Separator.divider(),
ExpandText(_rocket.description)
]),
);
}
Widget _specsCard(BuildContext context) {
final RocketVehicle _rocket = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.rocket.specifications.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context
.translate('spacex.vehicle.rocket.specifications.rocket_stages'),
_rocket.getStages(context),
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.rocket.specifications.height'),
_rocket.getHeight,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.specifications.diameter'),
_rocket.getDiameter,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.specifications.mass'),
_rocket.getMass(context),
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.rocket.stage.fairing_height'),
_rocket.fairingHeight(context),
),
RowItem.text(
context.translate('spacex.vehicle.rocket.stage.fairing_diameter'),
_rocket.fairingDiameter(context),
),
]),
);
}
Widget _payloadsCard(BuildContext context) {
final RocketVehicle _rocket = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.rocket.capability.title'),
child: RowLayout(
children: <Widget>[
for (final payloadWeight in _rocket.payloadWeights)
RowItem.text(
payloadWeight.name,
payloadWeight.getMass,
),
],
),
);
}
Widget _stages(BuildContext context) {
final RocketVehicle _rocket = context.watch<VehiclesCubit>().getVehicle(id);
return CardCell.body(
context,
title: context.translate('spacex.vehicle.rocket.stage.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.vehicle.rocket.stage.thrust_first_stage'),
_rocket.firstStage.getThrust,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.stage.fuel_amount'),
_rocket.firstStage.getFuelAmount(context),
),
RowItem.text(
context.translate('spacex.vehicle.rocket.stage.engines'),
_rocket.firstStage.getEngines(context),
),
RowItem.boolean(
context.translate('spacex.vehicle.rocket.stage.reusable'),
_rocket.firstStage.reusable,
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.rocket.stage.thrust_second_stage'),
_rocket.secondStage.getThrust,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.stage.fuel_amount'),
_rocket.secondStage.getFuelAmount(context),
),
RowItem.text(
context.translate('spacex.vehicle.rocket.stage.engines'),
_rocket.secondStage.getEngines(context),
),
RowItem.boolean(
context.translate('spacex.vehicle.rocket.stage.reusable'),
_rocket.secondStage.reusable,
),
]),
);
}
Widget _enginesCard(BuildContext context) {
final _engine =
(context.watch<VehiclesCubit>().getVehicle(id) as RocketVehicle).engine;
return CardCell.body(
context,
title: context.translate('spacex.vehicle.rocket.engines.title'),
child: RowLayout(children: <Widget>[
RowItem.text(
context.translate('spacex.vehicle.rocket.engines.model'),
_engine.getName,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.engines.thrust_weight'),
_engine.getThrustToWeight(context),
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.rocket.engines.fuel'),
_engine.getFuel,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.engines.oxidizer'),
_engine.getOxidizer,
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.rocket.engines.thrust_sea'),
_engine.getThrustSea,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.engines.thrust_vacuum'),
_engine.getThrustVacuum,
),
Separator.divider(),
RowItem.text(
context.translate('spacex.vehicle.rocket.engines.isp_sea'),
_engine.getIspSea,
),
RowItem.text(
context.translate('spacex.vehicle.rocket.engines.isp_vacuum'),
_engine.getIspVacuum,
),
]),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/vehicles/vehicle.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../cubits/index.dart';
import '../general/index.dart';
import 'index.dart';
class VehiclePage extends StatelessWidget {
final String vehicleId;
static const route = '/vehicle';
const VehiclePage({Key key, this.vehicleId}) : super(key: key);
@override
Widget build(BuildContext context) {
switch (context.watch<VehiclesCubit>().getVehicle(vehicleId).type) {
case 'rocket':
return RocketPage(vehicleId);
case 'capsule':
return DragonPage(vehicleId);
case 'ship':
return ShipPage(vehicleId);
case 'roadster':
return RoadsterPage(vehicleId);
default:
return ErrorScreen();
}
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/general/index.dart | export 'about.dart';
export 'changelog.dart';
export 'error.dart';
export 'index.dart';
export 'settings.dart';
export 'start.dart';
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/general/about.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:in_app_review/in_app_review.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:row_collection/row_collection.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// Constant list of all translators
const List<Map<String, String>> _translators = [
{'name': 'Jesús Rodríguez', 'language': 'English'},
{'name': 'Jesús Rodríguez', 'language': 'Español'},
{'name': '/u/OuterSpaceCitizen', 'language': 'Portugues'},
{'name': 'loopsun', 'language': '简体中文'},
{'name': 'Charlie Merland', 'language': 'Français'},
{'name': 'Tommi Avery', 'language': 'Italiano'},
{'name': 'Fatur Rahman S', 'language': 'Bahasa Indonesia'},
{'name': 'Patrick Kilter', 'language': 'Deutsch'},
];
/// This view contains a list with useful
/// information about the app & its developer.
class AboutScreen extends StatefulWidget {
const AboutScreen({Key key}) : super(key: key);
static const route = '/about';
@override
_AboutScreenState createState() => _AboutScreenState();
}
class _AboutScreenState extends State<AboutScreen> {
PackageInfo _packageInfo;
@override
void initState() {
super.initState();
_initPackageInfo();
}
// Gets information about the app itself
Future<void> _initPackageInfo() async {
final PackageInfo info = await PackageInfo.fromPlatform();
setState(() => _packageInfo = info);
}
@override
Widget build(BuildContext context) {
return SimplePage(
title: context.translate('app.menu.about'),
body: ListView(children: <Widget>[
HeaderText(
context.translate('about.headers.about'),
head: true,
),
ListCell.icon(
icon: Icons.info_outline,
title: context.translate(
'about.version.title',
parameters: {'version': _packageInfo?.version ?? '1.0'},
),
subtitle: context.translate('about.version.body'),
onTap: () => Navigator.pushNamed(context, '/changelog'),
),
Separator.divider(indent: 72),
ListCell.icon(
icon: Icons.star_border,
title: context.translate('about.review.title'),
subtitle: context.translate('about.review.body'),
onTap: () async {
final inAppReview = InAppReview.instance;
if (await inAppReview.isAvailable()) {
inAppReview.requestReview();
}
},
),
Separator.divider(indent: 72),
ListCell.icon(
icon: Icons.public,
title: context.translate('about.free_software.title'),
subtitle: context.translate('about.free_software.body'),
onTap: () => context.openUrl(Url.appSource),
),
HeaderText(context.translate('about.headers.author')),
ListCell.icon(
icon: Icons.person_outline,
title: context.translate('about.author.title'),
subtitle: context.translate('about.author.body'),
onTap: () => context.openUrl(Url.authorProfile),
),
Separator.divider(indent: 72),
Builder(
builder: (context) => ListCell.icon(
icon: Icons.cake_outlined,
title: context.translate('about.patreon.title'),
subtitle: context.translate('about.patreon.body'),
onTap: () => showPatreonDialog(context),
),
),
Separator.divider(indent: 72),
ListCell.icon(
icon: Icons.mail_outline,
title: context.translate('about.email.title'),
subtitle: context.translate('about.email.body'),
onTap: () => context.openUrl(Url.emailUrl),
),
HeaderText(context.translate('about.headers.credits')),
ListCell.icon(
icon: Icons.translate,
title: context.translate('about.translations.title'),
subtitle: context.translate('about.translations.body'),
onTap: () => showBottomRoundDialog(
context: context,
title: context.translate('about.translations.title'),
padding: EdgeInsets.zero,
children: [
for (final translation in _translators)
ListCell(
title: translation['name'],
subtitle: translation['language'],
contentPadding: EdgeInsets.symmetric(
horizontal: 20,
),
dense: true,
)
],
),
),
Separator.divider(indent: 72),
ListCell.icon(
icon: Icons.code,
title: context.translate('about.flutter.title'),
subtitle: context.translate('about.flutter.body'),
onTap: () => context.openUrl(Url.flutterPage),
),
Separator.divider(indent: 72),
ListCell.icon(
icon: Icons.folder_open,
title: context.translate('about.credits.title'),
subtitle: context.translate('about.credits.body'),
onTap: () => context.openUrl(Url.apiSource),
),
Separator.divider(indent: 72),
]),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/general/error.dart | import 'package:big_tip/big_tip.dart';
import 'package:flutter/material.dart';
/// Screen that is displayed when the routing system
/// throws an error (404 screen).
class ErrorScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: BigTip(
title: Text('An error ocurred'),
subtitle: Text('This page is not available'),
action: Text('GO BACK'),
actionCallback: () => Navigator.pop(context),
child: Icon(Icons.error_outline),
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/general/settings.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:row_collection/row_collection.dart';
import 'package:system_setting/system_setting.dart';
import '../../../cubits/index.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// Here lays all available options for the user to configurate.
class SettingsScreen extends StatelessWidget {
const SettingsScreen({Key key}) : super(key: key);
static const route = '/settings';
@override
Widget build(BuildContext context) {
return SimplePage(
title: context.translate('app.menu.settings'),
body: ListView(
children: <Widget>[
HeaderText(
context.translate('settings.headers.general'),
head: true,
),
BlocConsumer<ThemeCubit, ThemeState>(
listener: (context, state) => Navigator.of(context).pop(),
builder: (context, state) => ListCell.icon(
icon: Icons.palette,
title: context.translate('settings.theme.title'),
subtitle: context.translate('settings.theme.body'),
onTap: () => showBottomRoundDialog(
context: context,
title: context.translate('settings.theme.title'),
padding: EdgeInsets.zero,
children: <Widget>[
RadioCell<ThemeState>(
title: context.translate('settings.theme.theme.dark'),
groupValue: state,
value: ThemeState.dark,
onChanged: (value) => updateTheme(context, value),
),
RadioCell<ThemeState>(
title: context.translate('settings.theme.theme.black'),
groupValue: state,
value: ThemeState.black,
onChanged: (value) => updateTheme(context, value),
),
RadioCell<ThemeState>(
title: context.translate('settings.theme.theme.light'),
groupValue: state,
value: ThemeState.light,
onChanged: (value) => updateTheme(context, value),
),
RadioCell<ThemeState>(
title: context.translate('settings.theme.theme.system'),
groupValue: state,
value: ThemeState.system,
onChanged: (value) => updateTheme(context, value),
),
],
),
),
),
Separator.divider(indent: 72),
BlocConsumer<ImageQualityCubit, ImageQuality>(
listener: (context, state) => Navigator.of(context).pop(),
builder: (context, state) => ListCell.icon(
icon: Icons.photo_filter,
title: context.translate('settings.image_quality.title'),
subtitle: context.translate('settings.image_quality.body'),
onTap: () => showBottomRoundDialog(
context: context,
title: context.translate('settings.image_quality.title'),
padding: EdgeInsets.zero,
children: <Widget>[
RadioCell<ImageQuality>(
title:
context.translate('settings.image_quality.quality.low'),
groupValue: state,
value: ImageQuality.low,
onChanged: (value) => updateImageQuality(context, value),
),
RadioCell<ImageQuality>(
title: context
.translate('settings.image_quality.quality.medium'),
groupValue: state,
value: ImageQuality.medium,
onChanged: (value) => updateImageQuality(context, value),
),
RadioCell<ImageQuality>(
title: context
.translate('settings.image_quality.quality.high'),
groupValue: state,
value: ImageQuality.high,
onChanged: (value) => updateImageQuality(context, value),
),
],
),
),
),
Separator.divider(indent: 72),
BlocConsumer<BrowserCubit, BrowserType>(
listener: (context, state) => Navigator.of(context).pop(),
builder: (context, state) => ListCell.icon(
icon: Icons.language,
title: context.translate('settings.internal_browser.title'),
subtitle: context.translate(
state == BrowserType.inApp
? 'settings.internal_browser.internal_browser'
: 'settings.internal_browser.external_browser',
),
onTap: () => showBottomRoundDialog(
context: context,
title: context.translate(
'settings.internal_browser.title',
),
padding: EdgeInsets.zero,
children: <Widget>[
RadioCell<BrowserType>(
title: context.translate(
'settings.internal_browser.internal_browser',
),
groupValue: state,
value: BrowserType.inApp,
onChanged: (value) => updateBrowserType(context, value),
),
RadioCell<BrowserType>(
title: context.translate(
'settings.internal_browser.external_browser',
),
groupValue: state,
value: BrowserType.system,
onChanged: (value) => updateBrowserType(context, value),
),
],
),
),
),
HeaderText(context.translate('settings.headers.services')),
ListCell.icon(
icon: Icons.notifications,
title: context.translate('settings.notifications.title'),
subtitle: context.translate('settings.notifications.body'),
onTap: () => SystemSetting.goto(SettingTarget.NOTIFICATION),
),
Separator.divider(indent: 72),
],
),
);
}
static void updateTheme(BuildContext context, ThemeState value) =>
context.read<ThemeCubit>().theme = value;
static void updateImageQuality(BuildContext context, ImageQuality value) =>
context.read<ImageQualityCubit>().imageQuality = value;
static void updateBrowserType(BuildContext context, BrowserType value) =>
context.read<BrowserCubit>().browserType = value;
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/general/start.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:quick_actions/quick_actions.dart';
import '../../../cubits/index.dart';
import '../../../utils/index.dart';
import '../tabs/index.dart';
/// This view holds all tabs & its models: home, vehicles, upcoming & latest launches, & company tabs.
class StartScreen extends StatefulWidget {
static const route = '/';
@override
State<StatefulWidget> createState() => _StartScreenState();
}
class _StartScreenState extends State<StartScreen> {
int _currentIndex = 0;
@override
void initState() {
super.initState();
try {
// Reading app shortcuts input
final QuickActions quickActions = QuickActions();
quickActions.initialize((type) {
switch (type) {
case 'vehicles':
setState(() => _currentIndex = 1);
break;
case 'upcoming':
setState(() => _currentIndex = 2);
break;
case 'latest':
setState(() => _currentIndex = 3);
break;
default:
setState(() => _currentIndex = 0);
}
});
Future.delayed(Duration.zero, () async {
// Setting app shortcuts
await quickActions.setShortcutItems(<ShortcutItem>[
ShortcutItem(
type: 'vehicles',
localizedTitle: context.translate('spacex.vehicle.icon'),
icon: 'action_vehicle',
),
ShortcutItem(
type: 'upcoming',
localizedTitle: context.translate('spacex.upcoming.icon'),
icon: 'action_upcoming',
),
ShortcutItem(
type: 'latest',
localizedTitle: context.translate('spacex.latest.icon'),
icon: 'action_latest',
),
]);
});
} catch (_) {
debugPrint('could set quick actions');
}
}
@override
Widget build(BuildContext context) {
try {
context.watch<NotificationsCubit>()?.updateNotifications(
context,
nextLaunch: LaunchUtils.getUpcomingLaunch(
context.watch<LaunchesCubit>().state.value,
),
);
} catch (_) {
debugPrint('could set notifications');
}
return Scaffold(
body: IndexedStack(index: _currentIndex, children: [
HomeTab(),
VehiclesTab(),
LaunchesTab(LaunchType.upcoming),
LaunchesTab(LaunchType.latest),
CompanyTab(),
]),
bottomNavigationBar: BottomNavigationBar(
selectedItemColor: Theme.of(context).brightness == Brightness.light
? Theme.of(context).primaryColor
: Theme.of(context).accentColor,
type: BottomNavigationBarType.fixed,
onTap: (index) => _currentIndex != index
? setState(() => _currentIndex = index)
: null,
currentIndex: _currentIndex,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: context.translate('spacex.home.icon'),
icon: Icon(Icons.home),
),
BottomNavigationBarItem(
label: context.translate('spacex.vehicle.icon'),
icon: SvgPicture.asset(
'assets/icons/capsule.svg',
colorBlendMode: BlendMode.srcATop,
width: 24,
height: 24,
color: _currentIndex != 1
? Theme.of(context).brightness == Brightness.light
? Theme.of(context).textTheme.caption.color
: Colors.black26
: Theme.of(context).brightness == Brightness.light
? Theme.of(context).primaryColor
: Theme.of(context).accentColor,
),
),
BottomNavigationBarItem(
label: context.translate('spacex.upcoming.icon'),
icon: Icon(Icons.access_time),
),
BottomNavigationBarItem(
label: context.translate('spacex.latest.icon'),
icon: Icon(Icons.library_books),
),
BottomNavigationBarItem(
label: context.translate('spacex.company.icon'),
icon: Icon(Icons.location_city),
),
],
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui/views | mirrored_repositories/spacex-go/lib/ui/views/general/changelog.dart | import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../../../cubits/changelog.dart';
import '../../../utils/index.dart';
import '../../widgets/index.dart';
/// This screen loads the [CHANGELOG.md] file from GitHub,
/// and displays its content, using the Markdown plugin.
class ChangelogScreen extends StatelessWidget {
static const route = '/changelog';
@override
Widget build(BuildContext context) {
return RequestSimplePage<ChangelogCubit, String>(
title: context.translate('about.version.changelog'),
childBuilder: (context, state, value) => Markdown(
data: value,
onTapLink: (_, url, __) => context.openUrl(url),
styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context)).copyWith(
blockSpacing: 10,
h2: Theme.of(context).textTheme.subtitle1.copyWith(
fontWeight: FontWeight.bold,
),
p: Theme.of(context).textTheme.bodyText2.copyWith(
color: Theme.of(context).textTheme.caption.color,
),
),
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/launch_cell.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:row_collection/row_collection.dart';
import '../../models/index.dart';
import '../views/launches/index.dart';
import 'index.dart';
class LaunchCell extends StatelessWidget {
final Launch launch;
const LaunchCell(this.launch, {Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(children: <Widget>[
ListCell(
leading: ProfileImage.small(launch.patchUrl),
title: launch.name,
subtitle: launch.getLaunchDate(context),
trailing: TrailingText(launch.getNumber),
onTap: () => Navigator.pushNamed(
context,
LaunchPage.route,
arguments: {'id': launch.id},
),
),
Separator.divider(indent: 72)
]);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/responsive_page.dart | import 'package:flutter/material.dart';
class ResponsivePage extends StatelessWidget {
final Widget child;
final double width;
final Size breakpoint;
final Duration transformDuration;
final Curve transformationCurve;
const ResponsivePage({
Key key,
@required this.child,
this.width = 560,
this.breakpoint = const Size(600, 600),
this.transformDuration = const Duration(milliseconds: 500),
this.transformationCurve = Curves.easeInOutCubic,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final currentSize = MediaQuery.of(context).size;
final isMobile = currentSize.width < breakpoint.width ||
currentSize.height < breakpoint.height;
return AnimatedContainer(
duration: transformDuration,
curve: transformationCurve,
padding: isMobile
? EdgeInsets.zero
: EdgeInsets.symmetric(
horizontal: (currentSize.width - width) / 2,
vertical: 96,
),
child: isMobile
? child
: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: child,
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/achievement_cell.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:row_collection/row_collection.dart';
import '../../models/achievement.dart';
import '../../utils/index.dart';
class AchievementCell extends StatelessWidget {
final Achievement achievement;
final int index;
const AchievementCell({
Key key,
this.achievement,
this.index,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
DetailsCell(
leading: (index + 1).toString(),
title: achievement.name,
subtitle: achievement.getDate,
body: achievement.details,
onTap: achievement.hasLink
? () => context.openUrl(achievement.url)
: null,
),
Separator.divider(indent: 16),
],
);
}
}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.