Skip to content

Commit

Permalink
implement service get dicover movies
Browse files Browse the repository at this point in the history
  • Loading branch information
Goggxi committed Nov 17, 2022
1 parent dd3a4c0 commit 574712c
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 99 deletions.
128 changes: 29 additions & 99 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,119 +1,49 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:provider/provider.dart';
import 'package:yt_flutter_movie_db/app_constants.dart';
import 'package:yt_flutter_movie_db/movie/pages/movie_page.dart';
import 'package:yt_flutter_movie_db/movie/providers/movie_get_discover_provider.dart';
import 'package:yt_flutter_movie_db/movie/repostories/movie_repository.dart';
import 'package:yt_flutter_movie_db/movie/repostories/movie_repository_impl.dart';

void main() {
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
runApp(const MyApp());
FlutterNativeSplash.remove();
}

class MyApp extends StatelessWidget {
const MyApp({super.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'),
);
}
}
final dioOptions = BaseOptions(
baseUrl: AppConstants.baseUrl,
queryParameters: {'api_key': AppConstants.apiKey},
);

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final Dio dio = Dio(dioOptions);
final MovieRepository movieRepository = MovieRepositoryImpl(dio);

// 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();
runApp(App(movieRepository: movieRepository));
FlutterNativeSplash.remove();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
class App extends StatelessWidget {
const App({super.key, required this.movieRepository});

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++;
});
}
final MovieRepository movieRepository;

@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,
),
],
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => MovieGetDiscoverProvider(movieRepository),
),
],
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MoviePage(),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
61 changes: 61 additions & 0 deletions lib/movie/models/movie_model.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
class MovieResponseModel {
MovieResponseModel({
required this.page,
required this.results,
required this.totalPages,
required this.totalResults,
});

final int page;
final List<MovieModel> results;
final int totalPages;
final int totalResults;

factory MovieResponseModel.fromMap(Map<String, dynamic> json) =>
MovieResponseModel(
page: json["page"],
results: List<MovieModel>.from(
json["results"].map((x) => MovieModel.fromMap(x))),
totalPages: json["total_pages"],
totalResults: json["total_results"],
);
}

class MovieModel {
MovieModel({
this.backdropPath,
required this.id,
required this.originalTitle,
required this.overview,
required this.popularity,
this.posterPath,
required this.releaseDate,
required this.title,
required this.voteAverage,
required this.voteCount,
});

final String? backdropPath;
final int id;
final String originalTitle;
final String overview;
final double popularity;
final String? posterPath;
final DateTime releaseDate;
final String title;
final double voteAverage;
final int voteCount;

factory MovieModel.fromMap(Map<String, dynamic> json) => MovieModel(
backdropPath: json["backdrop_path"] ?? '',
id: json["id"],
originalTitle: json["original_title"],
overview: json["overview"],
popularity: json["popularity"].toDouble(),
posterPath: json["poster_path"] ?? '',
releaseDate: DateTime.parse(json["release_date"]),
title: json["title"],
voteAverage: json["vote_average"].toDouble(),
voteCount: json["vote_count"],
);
}
46 changes: 46 additions & 0 deletions lib/movie/pages/movie_page.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:yt_flutter_movie_db/movie/providers/movie_get_discover_provider.dart';

class MoviePage extends StatelessWidget {
const MoviePage({super.key});

@override
Widget build(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<MovieGetDiscoverProvider>().getDicover(context);
});

return Scaffold(
appBar: AppBar(
title: const Text('Movie DB'),
),
body: Consumer<MovieGetDiscoverProvider>(
builder: (_, provider, __) {
if (provider.isLoading) {
return const Center(
child: CircularProgressIndicator(),
);
}

if (provider.movies.isNotEmpty) {
return ListView.builder(
itemBuilder: (context, index) {
final movie = provider.movies[index];

return ListTile(
title: Text(movie.title),
subtitle: Text(movie.overview),
);
},
);
}

return const Center(
child: Text('Not Found Discover Movies'),
);
},
),
);
}
}
41 changes: 41 additions & 0 deletions lib/movie/providers/movie_get_discover_provider.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import 'package:flutter/material.dart';
import 'package:yt_flutter_movie_db/movie/models/movie_model.dart';
import 'package:yt_flutter_movie_db/movie/repostories/movie_repository.dart';

class MovieGetDiscoverProvider with ChangeNotifier {
final MovieRepository _movieRepository;

MovieGetDiscoverProvider(this._movieRepository);

bool _isLoading = false;
bool get isLoading => _isLoading;

final List<MovieModel> _movies = [];
List<MovieModel> get movies => _movies;

void getDicover(BuildContext context) async {
_isLoading = true;
notifyListeners();

final result = await _movieRepository.getDiscover();

result.fold(
(errorMessage) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(errorMessage),
));

_isLoading = false;
notifyListeners();
return;
},
(response) {
_movies.clear();
_movies.addAll(response.results);
_isLoading = false;
notifyListeners();
return null;
},
);
}
}
6 changes: 6 additions & 0 deletions lib/movie/repostories/movie_repository.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import 'package:dartz/dartz.dart';
import 'package:yt_flutter_movie_db/movie/models/movie_model.dart';

abstract class MovieRepository {
Future<Either<String, MovieResponseModel>> getDiscover({int page = 1});
}
33 changes: 33 additions & 0 deletions lib/movie/repostories/movie_repository_impl.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:yt_flutter_movie_db/movie/models/movie_model.dart';
import 'package:yt_flutter_movie_db/movie/repostories/movie_repository.dart';

class MovieRepositoryImpl implements MovieRepository {
final Dio _dio;

MovieRepositoryImpl(this._dio);

@override
Future<Either<String, MovieResponseModel>> getDiscover({int page = 1}) async {
try {
final result = await _dio.get(
'/discover/movie',
queryParameters: {'page': page},
);

if (result.statusCode == 200 && result.data != null) {
final model = MovieResponseModel.fromMap(result.data);
return Right(model);
}

return const Left('Error get discover movies');
} on DioError catch (e) {
if (e.response != null) {
return Left(e.response.toString());
}

return const Left('Another error on get discover movies');
}
}
}
7 changes: 7 additions & 0 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.5"
dartz:
dependency: "direct main"
description:
name: dartz
url: "https://pub.dartlang.org"
source: hosted
version: "0.10.1"
dio:
dependency: "direct main"
description:
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ dependencies:
flutter_native_splash: ^2.2.14
dio: ^4.0.6
provider: ^6.0.4
dartz: ^0.10.1

dev_dependencies:
flutter_test:
Expand Down

0 comments on commit 574712c

Please sign in to comment.