android - “总”变量未更新
问题描述
所以我制作了一个检测纸币价值的应用程序,每次检测到货币时,它的值都应该在“total”变量中更新。例如:假设我拍了一张 200 卢比钞票的照片,“总”变量应该增加 200。现在,如果我给一张 500 卢比的钞票拍照,总数应该是 700(200+500),但它显示的是 500,这意味着它没有存储之前的 200,并且又回到了 0。请有人帮忙,这似乎是一个非常小的错误,我尝试了很多,但徒劳无功。
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:torch_compat/torch_compat.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:tflite/tflite.dart';
int total = 0;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final cameras = await availableCameras();
final firstCamera = cameras.first;
runApp(
MaterialApp(
theme: ThemeData.dark(),
home: TakePictureScreen(
// Pass the appropriate camera to the TakePictureScreen widget.
camera: firstCamera,
),
),
);
}
class TakePictureScreen extends StatefulWidget {
final CameraDescription camera;
const TakePictureScreen({
Key key,
@required this.camera,
}) : super(key: key);
@override
_TakePictureScreenState createState() => _TakePictureScreenState();
}
class _TakePictureScreenState extends State<TakePictureScreen> {
CameraController _controller;
Future<void> _initializeControllerFuture;
@override
void initState() {
super.initState();
// To display the current output from the Camera,
// create a CameraController.
_controller = CameraController(
// Get a specific camera from the list of available cameras.
widget.camera,
// Define the resolution to use.
ResolutionPreset.high,
);
// Next, initialize the controller. This returns a Future.
_initializeControllerFuture = _controller.initialize();
}
@override
void dispose() {
// Dispose of the controller when the widget is disposed.
_controller.dispose();
TorchCompat.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Center(child: Text('Noteify'))),
// Wait until the controller is initialized before displaying the
// camera preview. Use a FutureBuilder to display a loading spinner
// until the controller has finished initializing.
body: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the Future is complete, display the preview.
return CameraPreview(_controller);
} else {
// Otherwise, display a loading indicator.
return Center(child: CircularProgressIndicator());
}
},
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Center(
child: Container(
height: 100.0,
width: 100.0,
child: FittedBox(
child: FloatingActionButton(
child: Icon(Icons.camera_alt),
// Provide an onPressed callback.
onPressed: () async {
// Take the Picture in a try / catch block. If anything goes wrong,
// catch the error.
try {
TorchCompat.turnOn();
// Ensure that the camera is initialized.
await _initializeControllerFuture;
// Construct the path where the image should be saved using the
// pattern package.
final path = join(
// Store the picture in the temp directory.
// Find the temp directory using the `path_provider` plugin.
(await getTemporaryDirectory()).path,
'${DateTime.now()}.png',
);
// Attempt to take a picture and log where it's been saved.
await _controller.takePicture(path);
TorchCompat.turnOff();
// If the picture was taken, display it on a new screen.
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DisplayPictureScreen(path),
),
);
} catch (e) {
// If an error occurs, log the error to the console.
print(e);
}
},
),
),
),
),
],
),
);
}
}
// A widget that displays the picture taken by the user.
class DisplayPictureScreen extends StatefulWidget {
final String imagePath;
DisplayPictureScreen(this.imagePath);
@override
_DisplayPictureScreenState createState() => _DisplayPictureScreenState();
}
class _DisplayPictureScreenState extends State<DisplayPictureScreen> {
List op;
Image img;
@override
void initState() {
super.initState();
loadModel().then((value) {
setState(() {});
});
img = Image.file(File(widget.imagePath));
classifyImage(widget.imagePath, total);
}
@override
Widget build(BuildContext context) {
// Image img = Image.file(File(widget.imagePath));
// classifyImage(widget.imagePath, total);
return Scaffold(
appBar: AppBar(title: Text('Display the Picture')),
// The image is stored as a file on the device. Use the `Image.file`
// constructor with the given path to display the image.
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(child: Center(child: img)),
SizedBox(
height: 20,
)
],
),
),
);
}
Future<void> runTextToSpeech(String outputMoney, int totalMoney) async {
FlutterTts flutterTts;
flutterTts = new FlutterTts();
if (outputMoney == "50 rupees") {
String tot = totalMoney.toString();
print(tot);
String speakString = "Fifty rupees, Your total is now rupees, $tot";
await flutterTts.setSpeechRate(0.3);
await flutterTts.awaitSpeakCompletion(true);
await flutterTts.speak(speakString);
}
if (outputMoney == "100 rupees") {
String tot = totalMoney.toString();
print(tot);
String speakString = "One Hundred rupees, Your total is now rupees, $tot";
await flutterTts.setSpeechRate(0.3);
await flutterTts.awaitSpeakCompletion(true);
await flutterTts.speak(speakString);
}
if (outputMoney == "200 rupees") {
String tot = totalMoney.toString();
print(tot);
String speakString = "Two Hundred rupees, Your total is now rupees, $tot";
await flutterTts.setSpeechRate(0.3);
await flutterTts.awaitSpeakCompletion(true);
await flutterTts.speak(speakString);
}
if (outputMoney == "500 rupees") {
String tot = totalMoney.toString();
print(tot);
String speakString =
"Five Hundred rupees, Your total is now rupees, $tot";
await flutterTts.setSpeechRate(0.3);
await flutterTts.awaitSpeakCompletion(true);
await flutterTts.speak(speakString);
}
if (outputMoney == "2000 rupees") {
String tot = totalMoney.toString();
print(tot);
String speakString =
"Two thousand rupees, Your total is now rupees, $tot";
await flutterTts.setSpeechRate(0.3);
await flutterTts.awaitSpeakCompletion(true);
await flutterTts.speak(speakString);
}
}
classifyImage(String image, int total) async {
var output = await Tflite.runModelOnImage(
path: image,
numResults: 5,
threshold: 0.5,
imageMean: 127.5,
imageStd: 127.5,
);
op = output;
if (op != null) {
if (op[0]["label"] == "50 rupees") {
total += 50;
runTextToSpeech("50 rupees", total);
}
if (op[0]["label"] == "100 rupees") {
total += 100;
runTextToSpeech("100 rupees", total);
}
if (op[0]["label"] == "200 rupees") {
total += 200;
runTextToSpeech("200 rupees", total);
}
if (op[0]["label"] == "500 rupees") {
total += 500;
runTextToSpeech("500 rupees", total);
}
if (op[0]["label"] == "2000 rupees") {
total += 2000;
runTextToSpeech("2000 rupees", total);
}
} else
runTextToSpeech("No note found", total);
}
loadModel() async {
await Tflite.loadModel(
model: "assets/model_unquant.tflite",
labels: "assets/labels.txt",
);
}
@override
void dispose() {
Tflite.close();
super.dispose();
}
}
解决方案
您有一个名为的全局变量total
和一个局部classifyImage
函数变量total
作为参数。当你这样做时total += 50;
,它默认引用局部变量。classifyImage
出于某种原因,您在完全没有必要时将全局变量传递给您的函数。
total
从函数定义中删除参数。
classifyImage(String image, int total) async {
至
classifyImage(String image) async {
推荐阅读
- complex-event-processing - Esper:为另一个事件之后发生的事件创建窗口
- python - matplotlib.pyplot plot 给出了在相同坐标中绘制的多个点。如何显示每个坐标有多少个点?
- php - 更改特定用户的 css 取决于 php 变量
- java - `scalac` 生成的每个 `.class` 文件是否也可以通过 `javac` 获得?
- java - 我怎样才能将 TextView(id) 作为双倍返回?
- javascript - 如何在加载输入背景上修复 chakra-ui 主题?
- r - ggplot2中geom_bar顶部的重叠文本
- xml - 使用 XSLT 和 xsl 将 XML 转换为 XML:for-each
- c# - ASP.NET Core MVC 3.1 - 使控制器无法访问外部是自己的区域
- vb.net - 在 loginscreen 中选择 accessdatabase,然后使用表中的凭据登录