Failed to run model, -67108857, java.lang.NegativeArrayS izeException: -67108857 - flutter

Has anyone solved this problem while using tflite package in flutter every model i used i get that issue of arrays?
Unhandled Exception: PlatformException(Failed to run model, -67108857, java.lang.NegativeArrayS
izeException: -67108857
How can i solve it.
Here is the basic code i was trying to run but landed into an error.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tflite/tflite.dart';
import 'package:image_picker/image_picker.dart';
import 'home.dart';
//import 'package:image/image.dart' as img;
void main() => runApp(MyApp());
const String ssd = "SSD MobileNet";
const String yolo = "Tiny YOLOv2";
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Object Detection App',
home: StaticImage(),
);
}
}
class StaticImage extends StatefulWidget {
#override
_StaticImageState createState() => _StaticImageState();
}
class _StaticImageState extends State<StaticImage> {
File _image;
List _recognitions;
bool _busy;
double _imageWidth, _imageHeight;
final picker = ImagePicker();
// this function loads the model
loadTfModel() async {
await Tflite.loadModel(
model: "assets/tflite/model_unquant.tflite",
labels: "assets/tflite/label.txt",
);
}
// this function detects the objects on the image
detectObject(File image) async {
var recognitions = await Tflite.detectObjectOnImage(
path: image.path, // required
model: "SSDMobileNet",
imageMean: 127.5,
imageStd: 127.5,
threshold: 0.4, // defaults to 0.1
numResultsPerClass: 10,// defaults to 5
asynch: true // defaults to true
);
FileImage(image)
.resolve(ImageConfiguration())
.addListener((ImageStreamListener((ImageInfo info, bool _) {
setState(() {
_imageWidth = info.image.width.toDouble();
_imageHeight = info.image.height.toDouble();
});
})));
setState(() {
_recognitions = recognitions;
});
}
#override
void initState() {
super.initState();
_busy = true;
loadTfModel().then((val) {{
setState(() {
_busy = false;
});
}});
}
// display the bounding boxes over the detected objects
List<Widget> renderBoxes(Size screen) {
if (_recognitions == null) return [];
if (_imageWidth == null || _imageHeight == null) return [];
double factorX = screen.width;
double factorY = _imageHeight / _imageHeight * screen.width;
Color blue = Colors.blue;
return _recognitions.map((re) {
return Container(
child: Positioned(
left: re["rect"]["x"] * factorX,
top: re["rect"]["y"] * factorY,
width: re["rect"]["w"] * factorX,
height: re["rect"]["h"] * factorY,
child: ((re["confidenceInClass"] > 0.50))? Container(
decoration: BoxDecoration(
border: Border.all(
color: blue,
width: 3,
)
),
child: Text(
"${re["detectedClass"]} ${(re["confidenceInClass"] * 100).toStringAsFixed(0)}%",
style: TextStyle(
background: Paint()..color = blue,
color: Colors.white,
fontSize: 15,
),
),
) : Container()
),
);
}).toList();
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
List<Widget> stackChildren = [];
stackChildren.add(
Positioned(
// using ternary operator
child: _image == null ?
Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Please Select an Image"),
],
),
)
: // if not null then
Container(
child:Image.file(_image)
),
)
);
stackChildren.addAll(renderBoxes(size));
if (_busy) {
stackChildren.add(
Center(
child: CircularProgressIndicator(),
)
);
}
return Scaffold(
appBar: AppBar(
title: Text("Object Detector"),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
heroTag: "Fltbtn2",
child: Icon(Icons.camera_alt),
onPressed: getImageFromCamera,
),
SizedBox(width: 10,),
FloatingActionButton(
heroTag: "Fltbtn1",
child: Icon(Icons.photo),
onPressed: getImageFromGallery,
),
],
),
body: Container(
alignment: Alignment.center,
child:Stack(
children: stackChildren,
),
),
);
}
// gets image from camera and runs detectObject
Future getImageFromCamera() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if(pickedFile != null) {
_image = File(pickedFile.path);
} else {
print("No image Selected");
}
});
detectObject(_image);
}
// gets image from gallery and runs detectObject
Future getImageFromGallery() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if(pickedFile != null) {
_image = File(pickedFile.path);
} else {
print("No image Selected");
}
});
detectObject(_image);
}
}
This is the code i was trying to run
Image for error is here
name: ml_classifier
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
tflite: ^1.0.4
image_picker: ^0.6.1+8
image: ^2.1.4
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
# The following section is specific to Flutter.
flutter:
# To add assets to your application, add an assets section, like this:
assets:
- assets/tflite/model_unquant.tflite
- assets/tflite/label.txt

Related

How to take screenshot of entire screen outside of your FLUTTER DESKTOP app(mostly for Windows OS)?

I'm new to flutter. Now I am able to take screenshot for my entire desktop app screen using Screenshot package & storing that image to local storage.
But my requirement is to capture the screenshot of entire screen of the window, like if 2 applications are opened(1 Flutter + 1 any other app e.g. browser) in 1 screen, then we can able to take whole screen's screenshot not only flutter app.
Please help me on how to take entire window's screenshot in Windows OS desktop app?
If it's not possible directly from Flutter, then how to achieve this by implementing some native code with Flutter?
check this completely working as expected
bool _isAccessAllowed = false;
CapturedData? _lastCapturedData;
#override
void initState() {
super.initState();
_init();
}
void _init() async {
_isAccessAllowed = await ScreenCapturer.instance.isAccessAllowed();
}
void _handleClickCapture(CaptureMode mode) async {
Directory directory = await getApplicationDocumentsDirectory();
String imageName =
'Screenshot-${DateTime.now().millisecondsSinceEpoch}.png';
String imagePath =
'${directory.path}/screen_capturer_example/Screenshots/$imageName';
_lastCapturedData = await ScreenCapturer.instance.capture(
mode: mode,
imagePath: imagePath,
silent: true,
);
if (_lastCapturedData != null) {
// ignore: avoid_print
// print(_lastCapturedData!.toJson());
} else {
// ignore: avoid_print
print('User canceled capture');
}
setState(() {});
}
Widget _buildBody(BuildContext context) {
return PreferenceList(
children: <Widget>[
if (Platform.isMacOS)
PreferenceListSection(
children: [
PreferenceListItem(
title: const Text('isAccessAllowed'),
accessoryView: Text('$_isAccessAllowed'),
onTap: () async {
bool allowed =
await ScreenCapturer.instance.isAccessAllowed();
BotToast.showText(text: 'allowed: $allowed');
setState(() {
_isAccessAllowed = allowed;
});
},
),
PreferenceListItem(
title: const Text('requestAccess'),
onTap: () async {
await ScreenCapturer.instance.requestAccess();
},
),
],
),
PreferenceListSection(
title: const Text('METHODS'),
children: [
PreferenceListItem(
title: const Text('capture'),
accessoryView: Row(children: [
CupertinoButton(
child: const Text('region'),
onPressed: () {
_handleClickCapture(CaptureMode.region);
},
),
CupertinoButton(
child: const Text('screen'),
onPressed: () {
_handleClickCapture(CaptureMode.screen);
},
),
CupertinoButton(
child: const Text('window'),
onPressed: () {
_handleClickCapture(CaptureMode.window);
},
),
]),
),
],
),
if (_lastCapturedData != null && _lastCapturedData?.imagePath != null)
Container(
margin: const EdgeInsets.only(top: 20),
width: 400,
height: 400,
child: Image.file(
File(_lastCapturedData!.imagePath!),
),
),
],
);
}
// screen shot taken by the App.
You might try using this package: screen_capturer. It works on Windows, Linux and MacOS.
From the docs:
Example of usage:
import 'package:screen_capturer/screen_capturer.dart';
CapturedData? capturedData = await screenCapturer.capture(
mode: CaptureMode.screen, // screen, window
imagePath: '<path>',
);
CaptureMode.screen is to capture the entire screen.
The screenshot package which you mention is only for taking screenshots for widgets of your app not of whole screen.

How to implement live changes to widgets when using Floor in Flutter?

My Flutter app is using Floor for data management and I am unable to figure out a logic for implementing a listener for when changes happen in a certain table. The app is created for a restaurant management and the module I am struggling with is the Cart implementation. So when a user deletes an element from the cart, I would like the total value at the bottom of the screen to reflect the current total of the items.
The functionality of my implementation is that as follows:
Cart screen loads with loading the list of CartItems from Floor
Calculate the invoice items and the quantity and I display these items in a widget called the 'CartBlock'
I also calculate the cart total which is displayed at the bottom of the screen
Cart Screen:
class CartScreen extends StatelessWidget {
BlocDao dao;
BlocService service;
CartScreen({key, required this.dao, required this.service}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Cart'),
),
body: _buildBody(context, service, dao));
}
}
Widget _buildBody(BuildContext context, BlocService service, BlocDao dao) {
final user = FirebaseAuth.instance.currentUser;
String userId = user!.uid;
Future<List<CartItem>> fItems = BlocRepository.getCartItems(dao, userId);
return FutureBuilder(
future: fItems,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Text('Loading cart items...');
} else {
List<CartItem> items = snapshot.data! as List<CartItem>;
return SingleChildScrollView(
child: Column(
children: [
// CoverPhoto(service.name, service.imageUrl),
SizedBox(height: 20.0),
_displayCartItems(dao, items),
// _invoiceDetailsItem(dao),
SizedBox(height: 10),
_orderConfirmItem(context, items),
],
),
);
}
});
}
Widget _displayCartItems(BlocDao dao, List<CartItem> items) {
List<CartItem> billItems = _createBill(items);
return ListView.builder(
primary: false,
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: billItems == null ? 0 : billItems.length,
itemBuilder: (BuildContext ctx, int index) {
CartItem item = billItems[index];
return CartBlock(
cartItem: item,
dao: dao,
);
},
);
}
List<CartItem> _createBill(List<CartItem> items) {
List<CartItem> bill=[];
int j=0;
for(int i = 0; i<items.length; i++){
CartItem item = items[i];
if(i==0){
bill.insert(j, item);
j++;
continue;
}
// check if it is already present in bill
int checkIndex = -1;
checkIndex = getItemInBill(item.productId, bill);
if(checkIndex == -1){
// then item not present in bill
bill.insert(j, item);
j++;
} else {
// item is in bill
CartItem billItem = bill[checkIndex];
billItem.quantity++;
bill[checkIndex] = billItem;
}
}
return bill;
}
int getItemInBill(String productId, List<CartItem> bill) {
for(int i=0;i<bill.length;i++){
CartItem item = bill[i];
if(item.productId == productId){
return i;
}
}
return -1;
}
Widget _orderConfirmItem(BuildContext context, List<CartItem> items) {
double _cartTotal = _calculateTotal(items);
return Card(
margin: EdgeInsets.all(15),
child: Padding(
padding: EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Total',
style: TextStyle(
fontSize: 20,
),
),
// spacer is a special widget which takes up all the space it can
Spacer(),
Chip(
label: Text(
'\u20B9${_cartTotal.toStringAsFixed(2)}',
style: TextStyle(
color:
Theme.of(context).cardColor),
),
backgroundColor: Theme.of(context).primaryColor,
),
// OrderButton(cart: cart),
],
),
),
);
}
double _calculateTotal(List<CartItem> items) {
double total = 0;
for(int i=0;i<items.length;i++){
total += items[i].productPrice;
}
return total;
}
Cart Block:
class CartBlock extends StatelessWidget {
CartItem cartItem;
BlocDao dao;
CartBlock({required this.cartItem, required this.dao});
#override
Widget build(BuildContext context) {
return Dismissible(
// the key is important to manage
key: ValueKey(cartItem.id),
background: Container(
color: Theme.of(context).errorColor,
child: Icon(
Icons.delete,
color: Colors.white,
size: 40,
),
alignment: Alignment.centerRight,
padding: EdgeInsets.only(right: 20),
margin: EdgeInsets.symmetric(
horizontal: 15,
vertical: 4,
),
),
// defines the swiping direction
direction: DismissDirection.endToStart,
confirmDismiss: (direction) {
return showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('Are you sure?'),
content: Text(
'Do you want to remove the item from the cart?',
),
actions: [
FlatButton(
child: Text('No'),
onPressed: () {
Navigator.of(ctx).pop(false);
},
),
FlatButton(
child: Text('Yes'),
onPressed: () {
Navigator.of(ctx).pop(true);
},
),
],
),
);
},
onDismissed: (direction) {
//direction to check which direction the swipe is going to
BlocRepository.deleteCartItems(dao, cartItem.productId);
Toaster.shortToast(cartItem.productName + ' has been removed.');
},
child: Card(
// symmetric is used to have different margins for left, right, top and bottom
margin: EdgeInsets.symmetric(
horizontal: 15,
vertical: 4,
),
child: Padding(
padding: EdgeInsets.all(8),
child: ListTile(
leading: CircleAvatar(
backgroundColor: Theme.of(context).highlightColor,
child: Padding(
padding: EdgeInsets.all(5),
child: FittedBox(
child: Text('\u20B9${cartItem.productPrice}'),
),
),
),
title: Text(cartItem.productName),
subtitle: Text('Total: \u20B9${(cartItem.productPrice * cartItem.quantity)}'),
trailing: Text('${cartItem.quantity} x'),
),
),
),
);
}
}
So when the onDismissed actions of deletion from the database is performed in CartBlock, I need the change to reflect in my total in the CartScreen but I am not sure how to make CartScreen listen to the changes.
Pubspec.yaml:
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
cloud_firestore: ^3.1.6
firebase_core: ^1.0.0
firebase_auth: ^1.0.0
firebase_storage: ^8.0.0
# location: ^4.3.0
# google_maps_flutter: ^0.5.17
# firebase_messaging: ^10.0.0
# firebase_core_platform_interface: ^4.0.0
image_picker: ^0.8.4+4
logger: ^1.1.0
# db management
floor: ^1.2.0
fluttertoast: ^8.0.9
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
floor_generator: ^1.2.0
build_runner: ^2.1.2
flutter_launcher_icons: "^0.9.2"
Snapshot of CartItem in the DB:
Screenshot of the Cart Screen:
I have worked with LiveData in android and I have been looking for similar implementation for flutter and floor but I have not been able to find anything useful. Any help would be highly appreciated and please do let me know if there is anything more that would be useful for a solution. Thank you in advance!

Initializing Flutter-Fire flutter Web

I can't figure out where is the problem output gives me Connection failed Here is the screen out put image. I'm trying to Initializing FlutterFire (Flutter Web). I'm doing it with the proper guidelines of official documentation https://firebase.flutter.dev/docs/overview#initializing-flutterfire.But can't figure out where I'm doing the mistake.
When I remove or comment on this part of codes it run.
// Check for errors
if (snapshot.hasError) {
return Center(
child: Text('Connection failed'),
);
}
Here is my main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Phatafut Admin Panel',
theme: ThemeData(
primaryColor: Colors.greenAccent,
),
home: MyHomePage(title: 'Phatafut Admin Panel'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
final _formKey = GlobalKey<FormState>();
// FirebaseServices _services = FirebaseServices();
var _usernameTextController = TextEditingController();
var _passwordTextController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
// // key:_formKey,
// appBar: AppBar(
// elevation: 0.0,
// title: Text('Grocery Store Admin Dashboard',style: TextStyle(color: Colors.white ),),
// centerTitle: true,
body: FutureBuilder(
// Initialize FlutterFire:
future: _initialization,
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
return Center(
child: Text('Connection failed'),
);
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.done) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF84c225), Colors.white],
stops: [1.0, 1.0],
begin: Alignment.topCenter,
end: Alignment(0.0, 0.0)),
),
child: Center(
child: Container(
width: 350,
height: 400,
child: Card(
elevation: 6,
shape: Border.all(color: Colors.green, width: 2),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
child: Column(
children: [
Image.asset('images/logo.png'),
Text(
'Grocery App ADMIN',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 20),
),
SizedBox(
height: 20,
),
TextFormField(
controller: _usernameTextController,
validator: (value) {
if (value.isEmpty) {
return 'Enter UserName';
}
return null;
},
decoration: InputDecoration(
labelText: 'UserName',
prefixIcon: Icon(Icons.person),
contentPadding: EdgeInsets.only(
left: 20, right: 20),
border: OutlineInputBorder(),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context)
.primaryColor,
width: 2))),
),
SizedBox(
height: 20,
),
TextFormField(
controller: _passwordTextController,
validator: (value) {
if (value.isEmpty) {
return 'Enter Password';
}
if (value.length < 6) {
return 'Minimum 6 character required';
}
return null;
},
obscureText: false,
decoration: InputDecoration(
labelText: 'Minimum 6 Characters',
prefixIcon: Icon(Icons.vpn_key_sharp),
hintText: 'Password',
contentPadding: EdgeInsets.only(
left: 20, right: 20),
border: OutlineInputBorder(),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context)
.primaryColor,
width: 2))),
),
],
),
),
Row(
children: [
Expanded(
child: TextButton(
style: TextButton.styleFrom(
primary: Colors.white,
backgroundColor: Colors.green,
onSurface: Colors.grey,
),
onPressed: () async {
if (_formKey.currentState.validate()) {
// _login(username: _usernameTextController.text, password: _passwordTextController.text);
}
},
child: Text(
'Login',
style: TextStyle(color: Colors.white),
)),
),
],
)
],
),
),
),
),
),
),
);
}
// Otherwise, show something whilst waiting for initialization to complete
return Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}
here is my index.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="admin_panel">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<title>admin_panel</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-analytics.js";
const firebaseConfig = {
apiKey: "********",
authDomain: "********",
projectId: "*********",
storageBucket: "************",
messagingSenderId: "******",
appId: "**************",
measurementId: "******"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
<script>
var serviceWorkerVersion = null;
var scriptLoaded = false;
function loadMainDartJs() {
if (scriptLoaded) {
return;
}
scriptLoaded = true;
var scriptTag = document.createElement('script');
scriptTag.src = 'main.dart.js';
scriptTag.type = 'application/javascript';
document.body.append(scriptTag);
}
if ('serviceWorker' in navigator) {
// Service workers are supported. Use them.
window.addEventListener('load', function () {
// Wait for registration to finish before dropping the <script> tag.
// Otherwise, the browser will load the script multiple times,
// potentially different versions.
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
navigator.serviceWorker.register(serviceWorkerUrl)
.then((reg) => {
function waitForActivation(serviceWorker) {
serviceWorker.addEventListener('statechange', () => {
if (serviceWorker.state == 'activated') {
console.log('Installed new service worker.');
loadMainDartJs();
}
});
}
if (!reg.active && (reg.installing || reg.waiting)) {
// No active web worker and we have installed or are installing
// one for the first time. Simply wait for it to activate.
waitForActivation(reg.installing ?? reg.waiting);
} else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
// When the app updates the serviceWorkerVersion changes, so we
// need to ask the service worker to update.
console.log('New service worker available.');
reg.update();
waitForActivation(reg.installing);
} else {
// Existing service worker is still good.
console.log('Loading app from service worker.');
loadMainDartJs();
}
});
// If service worker doesn't succeed in a reasonable amount of time,
// fallback to plaint <script> tag.
setTimeout(() => {
if (!scriptLoaded) {
console.warn(
'Failed to load app from service worker. Falling back to plain <script> tag.',
);
loadMainDartJs();
}
}, 4000);
});
} else {
// Service workers not supported. Just drop the <script> tag.
loadMainDartJs();
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
Here is my pubspec.yaml
name: admin_panel
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.10.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
firebase_core: ^1.5.0
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
Thanks in advance
Try adding these lines under <body> in your index.html, the documentation suggests using version 8.6.1 this way:
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js"></script>
And don't forget running flutter build web before deploying.

TRYING TO PLACE CALL DIRECTLY FROM FLUTTER: MissingPluginException(No implementation found for method callNumber

I want my app to place an automated call to a specific number when a certain condition arises. The two popular plugins are flutter_phone_direct_caller and url_launcher. Url launcher's problem is that the method will push the number to the dialer of your phone but wont start the call but flutter_phone_direct_caller claims it will initiate. This is the example in their documentation.
import 'package:flutter/material.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
void main() {
runApp(Scaffold(
body: Center(
child: RaisedButton(
onPressed: _callNumber,
child: Text('Call Number'),
),
),
));
}
_callNumber() async{
const number = '08592119XXXX'; //set the number here
bool res = await FlutterPhoneDirectCaller.callNumber(number);
}
this is the code for my page..when the button is pressed, call should initiate but for me, it returns an error.(my phone no. is XXXd out ,when i ran it i put in my actual no).
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vitality/components/bottomAppBar.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:vitality/components/biom.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
class HomeScreen extends StatefulWidget {
static const String id = 'home_screen';
final String docid;
final bool isCaretaker;
HomeScreen({#required this.docid, #required this.isCaretaker});
#override
_HomeScreenState createState() => _HomeScreenState();
}
_callNumber() async {
const number = '86065XXXXX'; //set the number here
bool res = await FlutterPhoneDirectCaller.callNumber(number);
}
class _HomeScreenState extends State<HomeScreen> {
final auth = FirebaseAuth.instance;
var pulse;
var temp;
#override
Widget build(BuildContext context) {
print('got here');
print(auth.currentUser.uid);
String id = ModalRoute.of(context).settings.arguments;
CollectionReference main = FirebaseFirestore.instance.collection('maindb');
main.doc(id).get().then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
print('Document exists on the database');
pulse = documentSnapshot['pulse'];
temp = documentSnapshot['temperature'];
}
});
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Color(0xFF602247),
toolbarHeight: 50.0,
centerTitle: true,
title: Text(
'HEALTH TRACKER',
style: Theme.of(context).textTheme.headline4,
)),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image:
NetworkImage('https://cdn.wallpapersafari.com/12/24/GiZRfh.jpg'),
fit: BoxFit.cover,
colorFilter: new ColorFilter.mode(
Colors.black.withOpacity(.7), BlendMode.dstATop),
)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(widget.docid),
Text({widget.isCaretaker}.toString()),
biom(which: 'pulse', image: 'pulse', docid: widget.docid),
RoundBorderText(text: 'PULSE'),
biom(which: 'temperature', image: 'temper', docid: widget.docid),
RoundBorderText(text: 'TEMPERATURE'),
SizedBox(height: 30.0),
FlatButton(
child: Text('test call'),
onPressed: () async {
FlutterPhoneDirectCaller.callNumber('5');
})
]),
),
bottomNavigationBar: bottomAppBar(id: widget.docid),
);
}
}
class RoundBorderText extends StatelessWidget {
final String text;
RoundBorderText({this.text});
#override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(
left: 40.0, right: 40.0, top: 8.0, bottom: 8.0),
decoration: BoxDecoration(
// border: Border.all(
// color: Colors.black,
// width: 1.0,
// ),
borderRadius: BorderRadius.all(Radius.circular(20))),
child: Text(text, style: Theme.of(context).textTheme.headline1));
}
}
E/flutter (23210): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: MissingPluginException(No implementation found for method callNumber on channel flutter_phone_direct_caller)
This plugin has 94% popularity so it works for most people. Does anyone know what the issue is?
The way flutter integrates with native functionality is that is creates what are called MethodChannels using which they can call functions that are registered inside native java code from dart.
So one reason this error might be coming is that your flutter code is not able to communicate with the native java code, means it is not finding any channel or it is not finding the method registered by the package through a channel there.
I suspect this could be a build issue.
Steps
Uninstall the app from your device.
Rebuild app again.
This should solve the issue.

How to share PDF files in flutter

There does not appear to be any pub.dev plugin that allows sharing of PDF files.
My app creates PDFs.. I want to be able to share these PDFs.
So far, it seems that all these plugins only support sharing of PNG's..
How should I share my PDF?
I've used package esys_flutter_share
var sharePdf = await file.readAsBytes();
await Share.file(
'PDF Document',
'project.pdf',
sharePdf.buffer.asUint8List(),
'*/*',
);
I finally achieved it by using the below package as esys_flutter_share no null safety.
path_provider: ^2.0.12
share_plus: ^6.3.1
screenshot: ^1.3.0
First creating the function==> widget to pdf
class _MyGoalDetailsState extends State<MyGoalDetails> {
List<GlobalKey> printKey = List<GlobalKey>.generate(100, (index) => GlobalKey(debugLabel: 'key_$index'),growable: false);
final doc = pw.Document();
// ========== Funtion() for widget to pdf ============
void _printScreen(int index) async {
final image = await WidgetWraper.fromKey(
key: printKey[index],
pixelRatio: 2.0,
);
final directory = await getTemporaryDirectory();
final file = File('${directory.path}/my_goal.pdf');
final pdf = pw.Document();
pdf.addPage(pw.Page(
build: (pw.Context context) {
return pw.Center(
child: pw.Image(image),
);
},
));
await file.writeAsBytes(await pdf.save());
await Share.shareFiles(
[file.path],
text: 'Check out my goal details',
subject: 'My goal details',
);
}
......................................
...................
Then wrap the widget which I want to pdf.
RepaintBoundary(
key: printKey[0],
child: Container(
color: Colors.white,
padding: const EdgeInsets.fromLTRB(15,15,15,0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [.................................
And onPress of my share button creating my pdf..
IconButton(
onPressed: () async {
_printScreen(0);
},
icon: const Icon(Icons.share),
),