import 'dart:async'; import 'dart:typed_data'; import 'package:flutter/services.dart'; import '../main.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'unit_details.dart'; import '../Widgets/photo_viewer.dart'; import 'package:barcode_scan2/barcode_scan2.dart'; import '../Model/unit.dart'; import '../Utils/db_helper.dart'; import '../Blocs/Units/List/list_unit_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class UnitsPage extends StatefulWidget { UnitsPage({Key? key}) : super(key: key); @override _UnitsState createState() => _UnitsState(); } class _UnitsState extends State with SingleTickerProviderStateMixin,RouteAware { List unitsRef = []; List BlobsRef = []; bool completed = false; int totalUnit = 0; final search_controller = new TextEditingController(); bool hideAppbar = false; String search = ''; late ListUnitBloc _unitBloc; Map _timeouts = {}; void debounce(Duration timeout, Function target, [List arguments = const []]) { if (_timeouts.containsKey(target)) { _timeouts[target]?.cancel(); } Timer timer = Timer(timeout, () { Function.apply(target, arguments); }); _timeouts[target] = timer; } void _onChanged(String val)async { search = search_controller.text; _unitBloc.add(ListUnit(search: search,completed: completed)); } Future scan() async { try { search = ''; setState(() => search_controller.text = search); ScanResult result = await BarcodeScanner.scan(); String barcode = result.rawContent; setState(() => this.search = barcode); } on PlatformException catch (e) { if (e.code == BarcodeScanner.cameraAccessDenied) { util.showFlushbar(context, 'The user did not grant the camera permission!',color: Colors.red); setState(() { this.search = ''; }); } else { util.showFlushbar(context, 'Unknown error: $e',color: Colors.red); setState(() => this.search = ''); } } on FormatException { setState(() => this.search = ''); } catch (e) { util.showFlushbar(context, 'Unknown error: $e',color: Colors.red); setState(() => this.search = ''); } setState(() => search_controller.text = search); } @override void initState() { super.initState(); _unitBloc = ListUnitBloc(); WidgetsBinding.instance!.addPostFrameCallback((_) async { if(locationStream==null)await util.streamLocation(context); else { if(locationStream!.isPaused) locationStream!.resume(); } }); } @override void didChangeDependencies() { super.didChangeDependencies(); routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute); } @override void dispose() { print('LocationStream paused'); if(locationStream!.isPaused)locationStream!.pause(); _unitBloc.close(); routeObserver.unsubscribe(this); super.dispose(); } // @override // void didPushNext() async { // //pushed from home // _unitBloc.add(ListUnit(search: search,completed: completed)); // } @override void didPopNext() async { //popped to home _unitBloc.add(ListUnit(search: search,completed: completed)); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: ()async{ if(hideAppbar) { setState(() { hideAppbar=false; search = ''; search_controller.text = ''; }); _unitBloc.add(ListUnit(search: search,completed: completed)); return false; } else { return true; } }, child: Scaffold( appBar: (hideAppbar)? AppBar( backgroundColor: Colors.white, leading: GestureDetector( onTap:()async{ setState(() { hideAppbar=false; search = ''; search_controller.text = ''; }); _unitBloc.add(ListUnit(search: search,completed: completed)); },child: Container(width: 20,child: Icon(Icons.arrow_back,color:Colors.grey))), title: Container( color: Colors.white, child: TextFormField( maxLines: 1, controller: search_controller, onChanged: (val) => debounce(const Duration(milliseconds: 300), _onChanged, [val]), decoration: InputDecoration.collapsed( hintText: 'Search..', ), ), ), actions: [ TextButton( onPressed: ()async{ await scan(); _unitBloc.add(ListUnit(search: search,completed: completed)); }, child: Icon(Icons.select_all,color:Colors.grey), ) ], ) :null, body: BlocProvider( create: (BuildContext context) => _unitBloc, child: BlocListener( bloc: _unitBloc, listener: (context,state){ if(state is ListUnitError){ util.showFlushbar(context, state.err,color: Colors.red); } }, child: Column( children: [ (hideAppbar)?Container():SizedBox(height: MediaQuery.of(context).size.height/25,), Expanded( child:Stack( children: [ Container( alignment: Alignment.topRight, child: BlocBuilder( bloc: _unitBloc, builder: (context, state) { if (state is ListUnitFinish){ unitsRef = state.units; BlobsRef = state.blobs; } else if(state is ListUnitInitial){ _unitBloc.add(ListUnit()); } if(state is ListUnitLoading){ return Center( child: Container( height: 15, width: 15, child: CircularProgressIndicator(), ), ); } else{ return (unitsRef.isEmpty) ? Container(padding: EdgeInsets.only(top: 10,left: 10,right: 10), child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Checkbox( value: completed, onChanged: (value)async{ setState(() { completed = value??false; }); _unitBloc.add(ListUnit(search: search,completed: completed)); }, ), Text('Completed') ], ), (completed||hideAppbar)?Container():Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Text('Unit : ',style: TextStyle(color: Colors.grey,fontSize: 15),), Text('${(unitsRef.where((element) => element.flag=='TRUE').length==unitsRef.length)?'Done':'${unitsRef.length-unitsRef.where((element) => element.flag=='TRUE').length}'}',style: TextStyle(color: (unitsRef.length==unitsRef.where((element) => element.flag=='TRUE').length)?Colors.green:Colors.black,fontWeight: FontWeight.bold,fontSize: 16),), Text(!(unitsRef.length==unitsRef.where((element) => element.flag=='TRUE').length)?' of':'',style: TextStyle(color: Colors.grey,fontSize: 15),), Text(!(unitsRef.length==unitsRef.where((element) => element.flag=='TRUE').length)?' ${unitsRef.length}':'',style: TextStyle(color: Colors.black,fontSize: 16,fontWeight: FontWeight.bold,),), ], ), ], ),) :ListView.builder( padding: EdgeInsets.only(bottom: 10), itemCount: unitsRef.length, shrinkWrap: false, itemBuilder: (context,index){ Uint8List? display; display = unitsRef[index].flag=='FALSE'?null:(BlobsRef.length==unitsRef.length)?BlobsRef[index]!.bytes:null; return Column( children: [ (index==0)?Container(padding: EdgeInsets.only(top: 10,left: 10,right: 10),alignment: Alignment.centerRight, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Checkbox( value: completed, onChanged: (value)async{ setState(() { completed = value??false; }); _unitBloc.add(ListUnit(search: search,completed: completed)); }, ), Text('Completed') ], ), (completed||hideAppbar)?Container():Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Text('Unit : ',style: TextStyle(color: Colors.grey,fontSize: 15),), Text('${(unitsRef.where((element) => element.flag=='TRUE').length==unitsRef.length)?'Done':'${unitsRef.length-unitsRef.where((element) => element.flag=='TRUE').length}'}',style: TextStyle(color: (unitsRef.length==unitsRef.where((element) => element.flag=='TRUE').length)?Colors.green:Colors.black,fontWeight: FontWeight.bold,fontSize: 16),), Text(!(unitsRef.length==unitsRef.where((element) => element.flag=='TRUE').length)?' of':'',style: TextStyle(color: Colors.grey,fontSize: 15),), Text(!(unitsRef.length==unitsRef.where((element) => element.flag=='TRUE').length)?' ${unitsRef.length}':'',style: TextStyle(color: Colors.black,fontSize: 16,fontWeight: FontWeight.bold,),), ], ), ], ),):Container(), Padding( padding: const EdgeInsets.only(left:10,right: 10,top: 10), child: Container( padding: EdgeInsets.all(5.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.white, boxShadow: [ BoxShadow( color: Colors.grey, blurRadius: 5.0, // has the effect of softening the shadow spreadRadius: 2.0, // has the effect of extending the shadow offset: Offset( 00.0, // horizontal, move right 10 2.0, // vertical, move down 10 ), ) ], border: Border.all(color: Colors.grey.withOpacity(0.5)), ), child:Row( children: [ Expanded( flex: 3, child: InkWell( onTap: ()async{ if(display==null){ await Navigator.push( context, MaterialPageRoute( builder: (context) => UnitDetails(unitsRef[index],), ), ); } else{ await Navigator.push(context, MaterialPageRoute(builder: (context) => PhotoViewer(display!,id: unitsRef[index].id.toString(),jenis: '',edit: false,))); } }, child: Hero(tag: unitsRef[index].id,child: Padding( padding: EdgeInsets.only(right: 10), child: Container(width: 100,height: 100,alignment: Alignment.center,child:(display==null)?Icon(Icons.crop_original,color: Colors.white,size: 80,):null, decoration: BoxDecoration( color: Colors.grey.withOpacity(0.5), image: (display!=null)?DecorationImage( image: MemoryImage(display),fit: BoxFit.cover,):null,)), )), )), Expanded( flex: 7, child: InkWell( onTap: ()async{ await Navigator.push( context, MaterialPageRoute( builder: (context) => UnitDetails(unitsRef[index],), ), ); }, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Rangka : ${unitsRef[index].rangka}'), Divider(height: 10,), Text('Tipe : ${unitsRef[index].tipe}'), Divider(height: 10,), Row( children: [ // Container(width: MediaQuery.of(context).size.width*0.35,child: Text('State : ${unitsRef[index].state}')), // Container(width: MediaQuery.of(context).size.width*0.5,child: Text('Tipe : ${unitsRef[index].tipe}',style: TextStyle(fontSize: 12),)), Text('Timestamp : ${unitsRef[index].timestamp}'), ], ), Divider(height: 10,), Row( children: [ Container(width: MediaQuery.of(context).size.width*0.35,child: Text('Warna : ${unitsRef[index].warna}')), Text('State : ${unitsRef[index].state}'), ], ) ], ), ), )), ], )), ), ], ); }, ); } }), ), ], ), ), ], ), ) ), floatingActionButton: FloatingActionButton( backgroundColor: Colors.indigo.withOpacity(0.8), onPressed: ()async{ setState(() { hideAppbar = !(hideAppbar); }); }, child: Icon(Icons.search,color:Colors.white), ), ), ); } }