Commit 1b3c6c28 authored by Ardi Baskoro's avatar Ardi Baskoro
Browse files

Basic modularization

parent c40d608b
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig"
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Generated.xcconfig"
# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end
import 'package:flutter/material.dart';
class VoteColorHelper {
static Color getColor(double s) {
Color r = Colors.red;
if (s > 4.5 && s < 7) {
r = Colors.yellow;
} else if (s >= 7) {
r = Colors.green;
}
return r;
}
}
import 'package:flutter/material.dart';
import 'package:flutter_modular/ui/home_page.dart';
void main() {
runApp(const MyApp());
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
return const MaterialApp(
title: 'Movies App',
home: HomePage(title: 'Movies App'),
);
}
}
import 'dart:async';
import 'dart:convert';
import 'package:flutter_modular/network/model/movie.dart';
import 'package:http/http.dart' show Client;
class ApiProvider {
Client client = Client();
//TODO: Add your api key here
static const _apiKey = '6cbbb575d03419c61482de70c8706aae'; // please replace with your API KEY :)
static const String _baseUrl = 'http://api.themoviedb.org/3/movie';
Future<Movie> getMovieList() async {
final url = Uri.parse("$_baseUrl/popular?api_key=$_apiKey");
final response = await client.get(url);
if (response.statusCode == 200) {
return Movie.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load movie');
}
}
}
class Genres {
static Map<int, String> genres = {
10759: "Action & Adventure",
16: "Animation",
35: "Comedy",
80: "Crime",
99: "Documentary",
18: "Drama",
10751: "Family",
10762: "Kids",
9648: "Mystery",
10763: "News",
10764: "Reality",
10765: "Sci-Fi & Fantasy",
10766: "Soap",
10767: "Talk",
10768: "War & Politics",
37: "Western",
28: "Action",
12: "Adventure",
14: "Fantasy",
36: "History",
27: "Horror",
10402: "Music",
10749: "Romance",
878: "Science Fiction",
10770: "TV Movie",
53: "Thriller",
10752: "War",
};
}
class Movie {
Movie({
required this.page,
required this.results,
required this.totalPages,
required this.totalResults,
});
final int page;
final List<Result> results;
final int totalPages;
final int totalResults;
factory Movie.fromJson(Map<String, dynamic> json) => Movie(
page: json["page"],
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
totalPages: json["total_pages"],
totalResults: json["total_results"],
);
Map<String, dynamic> toJson() => {
"page": page,
"results": List<dynamic>.from(results.map((x) => x.toJson())),
"total_pages": totalPages,
"total_results": totalResults,
};
}
class Result {
Result({
required this.adult,
required this.backdropPath,
required this.genreIds,
required this.id,
required this.originalLanguage,
required this.originalTitle,
required this.overview,
required this.popularity,
required this.posterPath,
required this.releaseDate,
required this.title,
required this.video,
required this.voteAverage,
required this.voteCount,
});
final bool adult;
final String backdropPath;
final List<int> genreIds;
final int id;
final String originalLanguage;
final String originalTitle;
final String overview;
final double popularity;
final String posterPath;
final String releaseDate;
final String title;
final bool video;
final double voteAverage;
final int voteCount;
factory Result.fromJson(Map<String, dynamic> json) => Result(
adult: json["adult"],
backdropPath: json["backdrop_path"],
genreIds: List<int>.from(json["genre_ids"].map((x) => x)),
id: json["id"],
originalLanguage: json["original_language"],
originalTitle: json["original_title"],
overview: json["overview"],
popularity: json["popularity"].toDouble(),
posterPath: json["poster_path"],
releaseDate: json["release_date"],
title: json["title"],
video: json["video"],
voteAverage: json["vote_average"].toDouble(),
voteCount: json["vote_count"],
);
Map<String, dynamic> toJson() => {
"adult": adult,
"backdrop_path": backdropPath,
"genre_ids": List<dynamic>.from(genreIds.map((x) => x)),
"id": id,
"original_language": originalLanguage,
"original_title": originalTitle,
"overview": overview,
"popularity": popularity,
"poster_path": posterPath,
"release_date": releaseDate,
"title": title,
"video": video,
"vote_average": voteAverage,
"vote_count": voteCount,
};
}
import 'package:flutter/material.dart';
import 'package:flutter_modular/widget/movie_detail_header.dart';
import 'package:flutter_modular/widget/story_line.dart';
class DetailPage extends StatelessWidget {
final List<Widget> genre;
final String title;
final String imageBanner;
final String imagePoster;
final double rating;
final String overview;
const DetailPage({
Key? key,
required this.genre,
required this.title,
required this.imageBanner,
required this.imagePoster,
required this.rating,
required this.overview,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Stack(
children: <Widget>[
Column(
children: [
MovieDetailHeader(
title: title,
imageBanner: imageBanner,
imagePoster: imagePoster,
rating: rating,
genre: genre,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Storyline(overview),
),
const SizedBox(height: 50.0),
],
),
Positioned(
top: 20,
left: 5,
child: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.pop(context)),
),
],
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter_modular/network/api/api_provider.dart';
import 'package:flutter_modular/network/model/movie.dart';
import 'package:flutter_modular/ui/detail_page.dart';
import 'package:flutter_modular/widget/card_list_movie.dart';
import 'package:flutter_modular/widget/chip_genre_movie.dart';
class HomePage extends StatefulWidget {
final String title;
const HomePage({Key? key, required this.title}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(
widget.title,
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Color.fromRGBO(58, 66, 86, 1.0),
),
),
backgroundColor: Colors.white,
),
body: getListMovie(),
);
}
getListMovie() {
return Center(
child: FutureBuilder(
future: ApiProvider().getMovieList(),
builder: (context, AsyncSnapshot<Movie> snapshot) {
if (snapshot.hasData) {
return showListMovie(snapshot);
} else if (snapshot.hasError) {
return Text(
snapshot.error.toString(),
style: const TextStyle(color: Color.fromRGBO(58, 66, 86, 1.0)),
);
}
return const Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color.fromRGBO(58, 66, 86, 1.0))));
},
),
);
}
Widget showListMovie(AsyncSnapshot<Movie> snapshot) => ListView.builder(
itemCount: snapshot.data == null ? 0 : snapshot.data?.results.length,
itemBuilder: (BuildContext context, int index) {
final movie = snapshot.data!.results[index];
return GestureDetector(
child: CardListMovies(
image: 'https://image.tmdb.org/t/p/w185${movie.posterPath}',
title: movie.title,
vote: movie.voteAverage.toString(),
releaseDate: movie.releaseDate,
overview: movie.overview,
genre: movie.genreIds.take(3).map(buildGenreChip).toList(),
),
onTap: () {
Navigator.push(
context,
PageRouteBuilder(
transitionDuration: const Duration(milliseconds: 777),
pageBuilder: (BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation) {
return DetailPage(
title: movie.title,
imagePoster:
'https://image.tmdb.org/t/p/w185${movie.posterPath}',
rating: movie.voteAverage,
imageBanner:
'https://image.tmdb.org/t/p/original${movie.backdropPath}',
genre:
movie.genreIds.take(3).map(buildGenreChip).toList(),
overview: movie.overview,
);
}),
);
},
);
},
);
}
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class ArcBannerImage extends StatelessWidget {
// ignore: use_key_in_widget_constructors
const ArcBannerImage(this.imageUrl);
final String imageUrl;
@override
Widget build(BuildContext context) {
var screenWidth = MediaQuery.of(context).size.width;
return ClipPath(
clipper: ArcClipper(),
child: SizedBox(
width: screenWidth,
height: 230.0,
child: CachedNetworkImage(
fit: BoxFit.cover,
imageUrl: imageUrl,
errorWidget: (context, url, error) => const Icon(Icons.error),
),
)
);
}
}
class ArcClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
var path = Path();
path.lineTo(0.0, size.height - 30);
var firstControlPoint = Offset(size.width / 4, size.height);
var firstPoint = Offset(size.width / 2, size.height);
path.quadraticBezierTo(firstControlPoint.dx, firstControlPoint.dy,
firstPoint.dx, firstPoint.dy);
var secondControlPoint = Offset(size.width - (size.width / 4), size.height);
var secondPoint = Offset(size.width, size.height - 30);
path.quadraticBezierTo(secondControlPoint.dx, secondControlPoint.dy,
secondPoint.dx, secondPoint.dy);
path.lineTo(size.width, 0.0);
path.close();
return path;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/common/color_helper.dart';
class CardListMovies extends StatelessWidget {
final String image;
final String vote;
final String title;
final String releaseDate;
final List<Widget> genre;
final String overview;
const CardListMovies({
Key? key,
required this.image,
required this.vote,
required this.title,
required this.releaseDate,
required this.genre,
required this.overview,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(5),
child: Card(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// image
SizedBox(
width: 130,
height: 200,
child: CachedNetworkImage(
imageUrl: image,
errorWidget: (context, url, error) => const Icon(Icons.error),
),
),
Expanded(
child: Container(
width: 260,
padding: const EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
// circle vote average
SizedBox(
width: 40,
height: 40,
child: Stack(
children: <Widget>[
Center(
child: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: Colors.blueGrey,
borderRadius:
BorderRadius.circular(20)),
),
),