Unhandled Exception: PlatformException(Failed to run model, Interpreter busy, - flutter

why im getting this error, im trying to run a object detection app in flutter
while running im getting this error in run time, and the object text also not appear
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(Failed to run model, Interpreter busy, java.lang.RuntimeException: Interpreter busy
My code,
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:flutter_tflite/flutter_tflite.dart';
//import 'package:tflite/tflite.dart';
String result = "";
class CameraScreen extends StatefulWidget {
final CameraDescription camera;
CameraScreen(this.camera);
#override
_CameraScreenState createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen> {
loadModel() async {
await Tflite.loadModel(
model: "assets/mobilenet_v1_1.0_224.tflite",
labels: "assets/mobilenet_v1_1.0_224.txt");
}
late CameraController _controller;
late CameraImage imgCam;
late Future<void> _initializeControllerFuture;
#override
void initState() {
super.initState();
_controller = CameraController(widget.camera, ResolutionPreset.medium);
_initializeControllerFuture = _controller.initialize().then((value) => {
setState((() {
_controller.startImageStream((imageFromStream) => {
imgCam = imageFromStream,
runModel(),
});
}))
});
loadModel();
}
runModel() async {
if (imgCam != null) {
var recognition = await Tflite.runModelOnFrame(
bytesList: imgCam.planes.map((plane) {
return plane.bytes;
}).toList(),
imageHeight: imgCam.height,
imageWidth: imgCam.width,
imageMean: 127.5,
imageStd: 127.5,
rotation: 90,
numResults: 1,
threshold: 0.1,
asynch: true,
);
result = "yes";
recognition?.forEach((response) {
result += response["label"] +
" " +
(response["confidence"] as double).toStringAsFixed(2) +
"\n\n";
print(result);
print("\n\n\n\n\n\n\n\n\n\n");
});
setState(() {
result;
});
}
}
#override
void dispose() async {
_controller.dispose();
await Tflite.close();
super.dispose();
}
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final deviceRatio = size.width / size.height;
return Scaffold(
body: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the Future is complete, display the preview
return AspectRatio(
aspectRatio: deviceRatio,
child: CameraPreview(
child: Center(
child: Text(result),
),
_controller),
);
} else {
// Otherwise, display a loading indicator
return Center(child: CircularProgressIndicator());
}
}));
}
}

Related

WebView showing ERR_CONNECTION_REFUSED (using flutter)

I got this error while using webview in flutter.
error: ERR_CONNECTION_REFUSED
Here is my code:
import 'dart:async'; import 'dart:io';
import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:flutter/services.dart'; import 'package:mime/mime.dart'; import 'package:provider/provider.dart';
import 'package:num_plus_plus/src/backend/mathmodel.dart'; import 'package:num_plus_plus/src/pages/settingpage.dart';
class Server { class from inAppBrowser
late HttpServer _server;
int _port = 8080;
Server({int port = 8080}) { this._port = port; }
///Closes the server. Future<void> close() async { if (this._server != null) { await this._server.close(force: true); print('Server running on http://localhost:$_port closed'); this._server = null as HttpServer;
} }
Future<void> start() async { if (this._server != null) { throw Exception('Server already started on http://localhost:$_port');
}
var completer = new Completer(); runZoned(() { HttpServer.bind('127.0.0.1', _port, shared: true).then((server) { print('Server running on http://localhost:' + _port.toString());
this._server = server;
server.listen((HttpRequest request) async { var body = <int>[]; var path = request.requestedUri.path; path = (path.startsWith('/')) ? path.substring(1) : path; path += (path.endsWith('/')) ? 'index.html' : '';
try { body = (await rootBundle.load(path)).buffer.asUint8List(); catch (e) { print(e.toString()); request.response.close(); return;
}
var contentType = ['text', 'html']; if (!request.requestedUri.path.endsWith('/') && request.requestedUri.pathSegments.isNotEmpty) { var mimeType = lookupMimeType(request.requestedUri.path, headerBytes: body); if (mimeType != null) { contentType = mimeType.split('/');
}
}
request.response.headers.contentType = new ContentType(contentType[0], contentType[1], charset: 'utf-8'); request.response.add(body); request.response.close();
});
completer.complete();
}); onError: (e, stackTrace) => print('Error: $e $stackTrace'));
return completer.future; } }
class MathBox extends StatelessWidget { #override Widget build(BuildContext context) { final mathBoxController = Provider.of<MathBoxController>(context, listen: false); final mathModel = Provider.of<MathModel>(context, listen: false); final matrixModel = Provider.of<MatrixModel>(context, listen: false); final functionModel = Provider.of<FunctionModel>(context, listen: false); final mode = Provider.of<CalculationMode>(context, listen: false); return Stack( children: <Widget>[ WebView( onWebViewCreated: (controller) { controller.loadUrl("http://localhost:8080/assets/html/homepage.html"); mathBoxController.webViewController = controller;
}, onPageFinished: (s) { final setting = Provider.of<SettingModel>(context, listen: false); if (setting.initPage == 1) { mathBoxController.addExpression('\\\\bmatrix');
}
}, javascriptMode: JavascriptMode.unrestricted, javascriptChannels: Set.from([ JavascriptChannel( name: 'latexString', onMessageReceived: (JavascriptMessage message) { if (mode.value == Mode.Matrix) { matrixModel.updateExpression(message.message); else { if (message.message.contains(RegExp('x|y'))) { mode.changeMode(Mode.Function); functionModel.updateExpression(message.message); else { mode.changeMode(Mode.Basic); mathModel.updateExpression(message.message); mathModel.calcNumber();
}
}
}
), JavascriptChannel( name: 'clearable', onMessageReceived: (JavascriptMessage message) { mathModel.changeClearable(message.message == 'false'?false:true);
}
),
]),
), ClearAnimation(),
],
); } }
class ClearAnimation extends StatefulWidget { #override
_ClearAnimationState createState() => _ClearAnimationState(); }
class _ClearAnimationState extends State<ClearAnimation> with TickerProviderStateMixin {
late AnimationController animationController; late Animation animation;
#override void initState() { super.initState(); animationController = AnimationController(duration: const Duration(milliseconds: 500),vsync: this); final curve = CurvedAnimation(parent: animationController, curve: Curves.easeInOutCubic); animation = Tween<double>(begin: 0, end: 2000).animate(curve); Provider.of<MathBoxController>(context, listen: false).clearAnimationController = animationController; }
#override void dispose() { animationController.dispose(); super.dispose(); }
Widget _buildAnimation(BuildContext context, Widget? child) { return Positioned( top: 10-animation.value/2 as double, right: -animation.value/2, child: ClipOval( child: Container( height: animation.value, width: animation.value, color: Colors.blue[100],
),
),
); }
#override Widget build(BuildContext context) { return AnimatedBuilder( builder: _buildAnimation, animation: animation,
); } }
class MathBoxController {
late WebViewController _webViewController; late AnimationController clearAnimationController;
set webViewController(WebViewController controller) { this._webViewController = controller; }
void addExpression(String msg, {bool isOperator = false}) { assert(_webViewController != null);
_webViewController.evaluateJavascript("addCmd('$msg', {isOperator: ${isOperator.toString()}})"); }
void addString(String msg) { assert(_webViewController != null);
_webViewController.evaluateJavascript("addString('$msg')"); }
void equal() { assert(_webViewController != null);
_webViewController.evaluateJavascript("equal()"); }
void addKey(String key) { assert(_webViewController != null);
_webViewController.evaluateJavascript("simulateKey('$key')"); }
void deleteExpression() { assert(_webViewController != null);
_webViewController.evaluateJavascript("delString()"); }
void deleteAllExpression() { assert(_webViewController != null);
_webViewController.evaluateJavascript("delAll()"); }
}

Is there any solution for my code in Flutter?

I want to render all of the pdfs' first page as images and pass them to Home Screen. I make Splash Screen's duration to 30second. But I think it is not right because there can be hundreds of pdfs in someone's phone storage and Splash Screen's duration can be longer than 30seconds. So is there any solution to my problem? Here is my code. Enlighten me pls.
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:native_pdf_renderer/native_pdf_renderer.dart';
import 'package:splash_screen_view/SplashScreenView.dart';
import 'constant.dart';
import 'package:permission_handler/permission_handler.dart';
import 'home_screen.dart';
class Splashscreens extends StatefulWidget {
_SplashscreensState createState() => _SplashscreensState();
}
class _SplashscreensState extends State<Splashscreens> {
List<FileSystemEntity>? filepdf;
List<Uint8List>? imagepdf = [];
void initState() {
super.initState();
getFile();
}
getFile() async {
await Permission.storage.request();
final myDir = Directory('/storage/emulated/0/documents/');
filepdf = myDir.listSync(recursive: true, followLinks: true);
for (int index = 0; index < filepdf!.length; index++) {
final document = await PdfDocument.openFile(filepdf![index].path);
final page = await document.getPage(1);
final pageImage = await page.render(width: page.width, height: page.height);
setState(() {
imagepdf!.add(pageImage!.bytes);
});
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: SplashScreenView(
navigateRoute: HomeScreen(filepdf, imagepdf),
duration: 25000,
imageSize: 650,
imageSrc: "assets/image/jensenpdfviewerlogo.jpg",
colors: [
Colors.purple,
Colors.blue,
Colors.yellow,
Colors.red,
Colors.orange,
Color(0xFFECECEC)
],
pageRouteTransition: PageRouteTransition.SlideTransition,
text: "LOADING......",
textType: TextType.ColorizeAnimationText,
textStyle: fontStyle,
backgroundColor: Color(0xFF4E4AC2),
),
),
);
}
}
Here is my suggestion
class Splashscreens extends StatefulWidget {
_SplashscreensState createState() => _SplashscreensState();
}
class _SplashscreensState extends State<Splashscreens> {
List<FileSystemEntity>? filepdf;
List<Uint8List>? imagepdf = [];
Future<Map<String, dynamic>> getFile() async {
await Permission.storage.request();
final myDir = Directory('/storage/emulated/0/documents/');
filepdf = myDir.listSync(recursive: true, followLinks: true);
for (int index = 0; index < filepdf!.length; index++) {
final document = await PdfDocument.openFile(filepdf![index].path);
final page = await document.getPage(1);
final pageImage = await page.render(width: page.width, height: page.height);
setState(() {
imagepdf!.add(pageImage!.bytes);
});
}
var data = {
"file_pdf": filepdf,
"image_pdf": imagepdf
};
return data;
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: getFile(),
builder: (BuildContext context, AsyncSnapshot<Map<String, dynamic>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.done:
Map<String, dynamic> data = snapshot.data!;
List<FileSystemEntity>? _filePdf = data["file_pdf"];
List<Uint8List>? _imagepdf = data["image_pdf"];
return YourResultScreen();
default:
return Container();
}
}
);
}
}

A build function returned null. The offending widget is: StoryCamera

I'm trying to display the full camera display on this page and when I run it, it returns null. This is my first try, creating a camera page, so things might look all over the place.
StoryCamera.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
List<CameraDescription> cameras;
//CameraController controller;
class StoryCamera extends StatefulWidget {
final String currentUser;
StoryCamera({this.currentUser});
#override
_StoryCameraState createState() => _StoryCameraState();
}
class _StoryCameraState extends State<StoryCamera> {
CameraController _controller;
Future<void> _initializeControllerFuture;
bool isCameraReady = false;
bool showCapturedPhoto = false;
var ImagePath;
get pageStatus => 1;
#override
void initState() {
super.initState();
_initializeCamera();
}
Future<void> _initializeCamera() async {
final cameras = await availableCameras();
final firstCamera = cameras.first;
_controller = CameraController(firstCamera, ResolutionPreset.high);
_initializeControllerFuture = _controller.initialize();
if (!mounted) {
return Container();
}
setState(() {
isCameraReady = true;
});
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_controller != null
? _initializeControllerFuture = _controller.initialize()
: null; //on pause camera is disposed, so we need to call again "issue is only for android"
}
}
void onCaptureButtonPressed() async {
//on camera button press
try {
final path = join(
(await getTemporaryDirectory()).path, //Temporary path
'$pageStatus${DateTime.now()}.png',
);
ImagePath = path;
await _controller.takePicture(path); //take photo
setState(() {
showCapturedPhoto = true;
});
} catch (e) {
print(e);
}
}
#override
void dispose() {
_controller?.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final deviceRatio = size.width / size.height;
FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the Future is complete, display the preview.
return Stack(
children: <Widget>[
Center(
child: Transform.scale(
scale: _controller.value.aspectRatio / deviceRatio,
child: new AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: new CameraPreview(_controller),
),
),
),
],
);
} else {
return Container(
child:
CircularProgressIndicator()); // Otherwise, display a loading indicator.
}
},
);
}
}
The error also points to the page before it that navigates you to this page.
StoryPage.dart
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StoryCamera())),
Can anyone tell me why this is happening?
You need to add a return
return FutureBuilder<void>(

how to make this lazyload scrolling working with provider

it take about 7 days trying make a working example for lazyload listview with provider in flutter with real world example and it's still not working because i think something is missing
As a note : the first load , works good and when i scroll it's print (scroll) but nothing happened it's still in the same page
if i try to return _todolist variable in the _onScrollUpdated it not change page correctly and after three times i see this error
E/flutter ( 7713): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)]
Unhandled Exception: type 'String' is not a subtype of type
'List' E/flutter ( 7713): #0 TodoService.fetchTodos
(package:flutter_todo_provider/services/todo_service.dart:32:21)
json example
https://jsonformatter.org/52c83e
todos_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_todo_provider/helpers/http_exception.dart';
import 'package:provider/provider.dart';
import 'package:flutter_todo_provider/.env.dart';
import 'package:flutter_todo_provider/services/todo_service.dart';
class TodosScreen extends StatefulWidget {
#override
_TodosScreenState createState() => _TodosScreenState();
}
class _TodosScreenState extends State<TodosScreen> {
ScrollController _controller;
List<dynamic> _todoList;
bool _isLoading ;
#override
void initState() {
super.initState();
_controller = ScrollController();
_controller.addListener(_onScrollUpdated);
}
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(Configuration.AppName),
),
body: FutureBuilder(
future: _fetchListItems(),
builder: (context, snapshot){
if(snapshot.hasData){
return _listItems(snapshot.data);
}
return _buildProgressIndicator();
}
),
);
}
_fetchListItems() async {
try {
await Provider.of<TodoService>(context, listen: false).loadNextPage();
_todoList = Provider.of<TodoService>(context, listen: false).items;
} on HttpException catch (e) {
EasyLoading.showError(e.message);
}
return _todoList ;
}
Widget _listItems(data){
_isLoading = Provider.of<TodoService>(context, listen: false).isLoading ;
return ListView.builder(
controller: _controller,
itemCount: data.length ,
itemBuilder: (context, index) {
return ListTile(
title: Text(data[index].title),
subtitle:Text(data[index].content),
trailing: Icon(Icons.print),
);
},
);
}
Future<void> _onScrollUpdated() async {
print("Scroll11");
var maxScroll = _controller.position.maxScrollExtent;
var currentPosition = _controller.position.pixels;
if (currentPosition == maxScroll ) {
try {
await Provider.of<TodoService>(context, listen: false).loadNextPage();
_todoList = Provider.of<TodoService>(context, listen: false).items;
// return _todoList ; if use this line i see the error
} on HttpException catch (e) {
EasyLoading.showError(e.message);
}
}
}
Widget _buildProgressIndicator() {
_isLoading = Provider.of<TodoService>(context, listen: false).isLoading ;
return new Padding(
padding: const EdgeInsets.all(8.0),
child: new Center(
child: new Opacity(
opacity: _isLoading ? 1.0 : 00,
child: new CircularProgressIndicator(),
),
),
);
}
}
todo_service.dart
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_todo_provider/.env.dart';
import 'package:flutter_todo_provider/models/todo.dart';
class TodoService with ChangeNotifier {
bool isLoading = false;
bool isFetching = false;
int currentPage = 1;
int totalRows = 10;
List<Todo> items = [];
loadNextPage() async {
await fetchTodos(currentPage);
currentPage++;
notifyListeners();
}
Future fetchTodos(int currentPage) async {
try {
//404
var options = Options(headers: {
HttpHeaders.authorizationHeader: 'Basic ${Configuration.authToken}'
});
Map<String, dynamic> qParams = {
'current_page': currentPage,
};
Response response = await Dio().get('${Configuration.ApiUrl}/todos/my_todos', options: options, queryParameters: qParams);
List<dynamic> responseBode = response.data["data"];
responseBode.forEach(( dynamic json) {
items.add(Todo.fromJson(json));
});
notifyListeners();
} on DioError catch (e) {
print("Error Message" + e.response.statusMessage);
return items=[];
}
}
}
Here is the code:
class TodoScreen extends StatefulWidget {
// Your service goes here
// (the class extending ChangeNotifier)
#override
_TodoScreenState createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
final TodoService todoService = TodoService();
ScrollController _controller;
#override
void initState() {
super.initState();
_controller = ScrollController();
_controller.addListener(_onScrollUpdated);
loadNextPage();
}
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Configuration.AppName'),
),
body: ChangeNotifierProvider.value(
value: todoService,
child: Consumer<TodoService>(builder: (_, ctl, __) {
if (todoService.isLoading) {
return _buildProgressIndicator();
} else {
return _listItems(todoService.items);
}
}),
),
);
}
Widget _listItems(data) {
return ListView.builder(
controller: _controller,
itemCount: data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(data[index].title),
subtitle: Text(data[index].content),
trailing: Icon(Icons.print),
);
},
);
}
Widget _buildProgressIndicator() {
return new Padding(
padding: const EdgeInsets.all(8.0),
child: new Center(
child: CircularProgressIndicator(),
),
);
}
Future<void> _onScrollUpdated() async {
var maxScroll = _controller.position.maxScrollExtent;
var currentPosition = _controller.position.pixels;
if (currentPosition == maxScroll) {
todoService.loadNextPage();
}
}
}
Note that i didn't make changes to your service. The notifyListeners will do all the job for us.
When you are using Provider, the idea is to keep all your data inside the controller or service (the class that extends ChangeNitifier) and just use the variables with notifyListeners to change the behavior of your screen.
The screen needs to be listening for changes, for this we use the pair ChangeNotifierProvider.value with Consumer(builder: (_, ctl, __) {}).
Use ChangeNotifierProvider in some upper level of the widget tree and use Consumer only where you need the widget to be updated. You can even use more than one Consumer, they all just need to be under ChangeNotifierProvider.

Stop listening to a stream

This program works okay on first build.When I disconnect my device and reconnects it,it is showing, bad state:stream has already been listened to,
Probably error is generated by stream that listening to Bluetooth characteristic.Whats the work around?
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:vibration/vibration.dart';
StreamSubscription _scanSubscription;
StreamSubscription _deviceConnection;
Stream<List<int>> stream;
List<double> traceDust = List();
const String CHAR_UUID = "AA:48:F8:CC:07:12";
const String Device_Name = "myDevice";
const String CHARACTERISTIC_UUID = "00000000-0111-1000-4000-000000000000";
BluetoothDeviceState _state;
Map<DeviceIdentifier, ScanResult> scanResults = new Map();
List<BluetoothService> services = new List();
BluetoothCharacteristic characteristic;
FlutterBlue flutterBlue = FlutterBlue.instance;
BluetoothDevice device;
class SearchScreen extends StatefulWidget {
#override
_SearchScreenState createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
#override
void initState() {
super.initState();
_startScan();
}
#override
void dispose() {
super.dispose();
_stopScan();
_deviceConnection?.cancel();
_deviceConnection = null;
device.disconnect();
}
_startScan() {
_scanSubscription =
flutterBlue.scan(timeout: Duration(seconds: 4)).listen((scanResult) {
if (CHAR_UUID == scanResult.device.id.toString()) {
_stopScan();
_connect(scanResult.device);
print('connected');
}
}, onDone: _stopScan());
}
_stopScan() {
_scanSubscription?.cancel();
_scanSubscription = null;
}
_connect(BluetoothDevice d) async {
device = d;
await device.connect(autoConnect: true);
await device.discoverServices().then((value) {
setState(() {
services = value;
});
});
_turnOnCharacterService(services);
}
_turnOnCharacterService(List<BluetoothService> ser) async {
ser.forEach((service) {
service.characteristics.forEach((character) {
if (character.uuid.toString() == CHARACTERISTIC_UUID) {
character.setNotifyValue(!character.isNotifying);
setState(() {
stream = character.value;
});
}
});
});
}
String _dataParser(List<int> dataFromDevice) {
return utf8.decode(dataFromDevice);
}
vibrateOnAlert() async {
if (await Vibration.hasVibrator()) {
Vibration.vibrate(duration: 1000);
}
}
#override
Widget build(BuildContext context) {
return Container(
child: StreamBuilder<BluetoothDeviceState>(
stream: device.state,
initialData: BluetoothDeviceState.connecting,
builder: (context, snapshot) {
if (snapshot.data == BluetoothDeviceState.connected) {
return StreamBuilder<List<int>>(
stream: stream,
builder: (context, snapshot) {
var currentValue;
if (snapshot.hasError) {
return Text('Error');
}
if (snapshot.connectionState == ConnectionState.active) {
currentValue = _dataParser(snapshot.data);
traceDust.add(double.tryParse(currentValue) ?? 0);
if (currentValue.toString().compareTo('vibrate') == 0) {
vibrateOnAlert();
}
} else {
return Text('disconnected');
}
print('$currentValue');
return Text('connected');
});
}
return FlatButton(
color: Colors.white,
child: Text('reconnecct'),
onPressed: () {
setState(() {
flutterBlue.startScan(timeout: Duration(seconds: 2));
});
},
);
},
));
}
}
PS: Here flat button does nothing.Since connection state is a streambuilder it automatically reconnects and shows error.