Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:convert';
- import 'dart:developer';
- import 'package:cocreate/pages/store/components/categories_list.dart';
- import 'package:cocreate/shared/shared.dart';
- import 'package:cocreate/utils/colors.dart';
- import 'package:flutter/material.dart';
- import 'package:http/http.dart' as http;
- import 'dart:io';
- import 'package:dio/dio.dart';
- import 'package:flutter_local_notifications/flutter_local_notifications.dart';
- import 'package:open_file/open_file.dart';
- import 'package:path_provider/path_provider.dart';
- import 'package:flutter/foundation.dart';
- import 'package:permission_handler/permission_handler.dart';
- import 'package:path/path.dart' as path;
- class BodyStore extends StatefulWidget {
- BodyStore({Key key, this.title}) : super(key: key);
- final String title;
- @override
- _BodyStore createState() => _BodyStore();
- }
- class _BodyStore extends State<BodyStore> {
- //APIDATASTORE
- final String apiUrl = "https://storeapi.digi46.id/index";
- //APIAPK
- final String _fileUrl = "https://storeapi.digi46.id/index";
- final Dio _dio = Dio();
- final String _fileName = "";
- String _progress = "-";
- //progressbar
- FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
- @override
- void initState() {
- super.initState();
- flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
- final android = AndroidInitializationSettings('@mipmap/ic_launcher');
- final iOS = IOSInitializationSettings();
- final initSettings = InitializationSettings(android, iOS);
- flutterLocalNotificationsPlugin.initialize(initSettings,
- onSelectNotification: _onSelectNotification);
- }
- Future<void> _onSelectNotification(String json) async {
- final obj = jsonDecode(json);
- if (obj['isSuccess']) {
- OpenFile.open(obj['filePath']);
- } else {
- showDialog(
- context: context,
- builder: (_) => AlertDialog(
- title: Text('Error'),
- content: Text('${obj['error']}'),
- ),
- );
- }
- }
- Future<void> _showNotification(Map<String, dynamic> downloadStatus) async {
- final android = AndroidNotificationDetails(
- 'channel id', 'channel name', 'channel description',
- priority: Priority.High, importance: Importance.Max);
- final iOS = IOSNotificationDetails();
- final platform = NotificationDetails(android, iOS);
- final json = jsonEncode(downloadStatus);
- final isSuccess = downloadStatus['isSuccess'];
- await flutterLocalNotificationsPlugin.show(
- 0, // notification id
- isSuccess ? 'Success' : 'Failure',
- isSuccess
- ? 'File has been downloaded successfully!'
- : 'There was an error while downloading the file.',
- platform,
- payload: json);
- }
- Future<Directory> _getDownloadDirectory() async {
- // if (Platform.isAndroid) {
- // return await DownloadsPathProvider.downloadsDirectory;
- // }
- // in this example we are using only Android and iOS so I can assume
- // that you are not trying it for other platforms and the if statement
- // for iOS is unnecessary
- // iOS directory visible to user
- return await getApplicationDocumentsDirectory();
- }
- Future<bool> _requestPermissions() async {
- var permission = await PermissionHandler()
- .checkPermissionStatus(PermissionGroup.storage);
- if (permission != PermissionStatus.granted) {
- await PermissionHandler().requestPermissions([PermissionGroup.storage]);
- permission = await PermissionHandler()
- .checkPermissionStatus(PermissionGroup.storage);
- }
- return permission == PermissionStatus.granted;
- }
- void _onReceiveProgress(int received, int total) {
- if (total != -1) {
- setState(() {
- _progress = (received / total * 100).toStringAsFixed(0) + "%";
- });
- }
- }
- Future<void> _startDownload(String savePath, String tipeApk) async {
- Map<String, dynamic> result = {
- 'isSuccess': false,
- 'filePath': null,
- 'error': null,
- };
- try {
- final response = await _dio.download(_fileUrl + tipeApk, savePath,
- onReceiveProgress: _onReceiveProgress);
- result['isSuccess'] = response.statusCode == 200;
- result['filePath'] = savePath;
- } catch (ex) {
- result['error'] = ex.toString();
- } finally {
- await _showNotification(result);
- }
- log("$result");
- print("$result");
- }
- Future<void> _download(String tipeApk) async {
- final dir = await _getDownloadDirectory();
- final isPermissionStatusGranted = await _requestPermissions();
- if (isPermissionStatusGranted) {
- final savePath = path.join(dir.path, _fileName);
- await _startDownload(savePath, tipeApk);
- } else {
- // handle the scenario when user declines the permissions
- }
- print("")
- }
- Future<List<dynamic>> fetchDataStore() async {
- var data = await http.get(apiUrl);
- return json.decode(data.body)['Data'];
- }
- String _idApps(dynamic datastore) {
- return datastore['Idapps'];
- }
- String _appImg(dynamic datastore) {
- return datastore['Appimg'];
- }
- String _name(dynamic datastore) {
- return datastore['Apsname'];
- }
- String _appversion(dynamic datastore) {
- return datastore['Appversion'];
- }
- String _description(dynamic datastore) {
- return datastore['Description'];
- }
- String _operats(dynamic datastore) {
- return datastore['Operats'];
- }
- String _appName(dynamic datastore) {
- return datastore['Appname'];
- }
- String _createdAt(dynamic datastore) {
- return datastore['CreatedAt'];
- }
- @override
- Widget build(BuildContext context) {
- return Column(
- children: [
- Row(
- children: [
- Container(
- margin: EdgeInsets.all(kDefaultPadding),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- "Store",
- style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
- ),
- ),
- ),
- Container(
- margin: EdgeInsets.fromLTRB(250.0, 30.0, 10.0, 10.0),
- child: Align(
- alignment: Alignment.center,
- child: Text(
- '$_progress',
- ),
- ),
- ),
- ],
- ),
- CategoriesList(),
- Expanded(
- child: Stack(
- children: [
- Container(
- decoration: BoxDecoration(
- color: Colors.white,
- ),
- ),
- // Text(
- // '$_progress',
- // style: Theme.of(context).textTheme.display1,
- // ),
- // ListView.builder(
- // itemCount: 7,
- // itemBuilder: (context, index) => AppCard(),
- // )
- Container(
- child: FutureBuilder<List<dynamic>>(
- future: fetchDataStore(),
- builder: (BuildContext context, AsyncSnapshot snapshot) {
- if (snapshot.hasData) {
- // print(_age(snapshot.data[0]));
- return ListView.builder(
- padding: EdgeInsets.all(2),
- itemCount: snapshot.data.length,
- itemBuilder: (BuildContext context, int index) {
- Size size = MediaQuery.of(context).size;
- return Container(
- margin: EdgeInsets.symmetric(
- horizontal: kDefaultPadding, vertical: 10),
- // color: Colors.lightBlue,
- height: 100,
- child: Stack(
- alignment: AlignmentDirectional.topCenter,
- children: [
- Container(
- height: 100,
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(10),
- color: Colors.white,
- boxShadow: [
- BoxShadow(
- blurRadius: 6,
- offset: Offset(1, 3),
- color:
- Colors.black.withOpacity(0.2))
- ]),
- ),
- Positioned(
- left: 5,
- top: 8,
- child: Row(
- children: [
- Container(
- margin: EdgeInsets.all(5),
- height: 60,
- width: 60,
- // child: Image.asset(
- // "assets/apklogo2.png",
- // fit: BoxFit.cover,
- // ),
- child: Image.network(
- // "https://ulummudin.xyz/files/images/5fb202b53f48c20001968243.png",
- _appImg(snapshot.data[index]),
- fit: BoxFit.contain,
- ),
- ),
- Container(
- padding: EdgeInsets.all(8),
- margin: EdgeInsets.only(left: 10),
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Text(
- _name(snapshot.data[index]),
- overflow:
- TextOverflow.ellipsis,
- style:
- TextStyle(fontSize: 16),
- ),
- Text(
- _appversion(
- snapshot.data[index]),
- style: TextStyle(
- color: kAccentColor4),
- ),
- Text(
- _operats(
- snapshot.data[index]),
- style: TextStyle(
- color: kAccentColor4)),
- // Text(
- // '$_progress',
- // ),
- ],
- ),
- )
- ],
- )),
- Positioned(
- right: 0,
- child: SizedBox(
- height: 100,
- width: size.width - 330,
- child: Container(
- padding: EdgeInsets.symmetric(
- horizontal: kDefaultPadding),
- child: Image.asset(
- "assets/icon-download.png",
- ),
- ),
- )),
- InkWell(
- onTap: () => _download(
- _appName(snapshot.data[index]),
- ),
- // handle your onTap here
- child: Container(height: 200, width: 200),
- ),
- ],
- ),
- );
- });
- } else {
- return Center(
- child: CircularProgressIndicator(
- valueColor:
- new AlwaysStoppedAnimation<Color>(COLOR_GREEN),
- ));
- }
- },
- ),
- ),
- ],
- ),
- )
- ],
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement