我已經使用 stackoverflow 多年,但從來沒有費心去注冊自己,但我覺得時機終于到了。:)
我目前正在 Flutter 中做一個學校專案,我對此很陌生,現在偶然發現了一個問題。嘗試了各種方法,但我不斷收到此例外:
在構建 Home(dirty, state: _HomeState#9ab2f) 時拋出了以下 LateError:
LateInitializationError:欄位“_image@17109416”尚未初始化。
什么可能導致這個問題?這是我的代碼:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MaterialApp(
home: Home(),
// debugShowCheckedModeBanner: false, // Turns off the 'DEBUG' sign in the upper right corner
));
class Home extends StatefulWidget {
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
// Camera implementation
late File _image;
final ImagePicker _picker = ImagePicker();
Future getImage() async {
final image = await _picker.pickImage(source: ImageSource.camera);
setState(() {
_image = File(image!.path);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 90,
title: const Text(
'School project',
style: TextStyle(
fontSize: 25.0,
//fontFamily: '', // change the font?
),
),
centerTitle: true,
backgroundColor: Colors.green[600],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Write or scan',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
)
),
const SizedBox(height: 50.0),
ElevatedButton.icon(
onPressed: () {
print('write'); // test
},
icon: const Icon(Icons.person_add_alt_rounded),
label: const Text('Write'),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green[500]),
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 22)),
)
),
const SizedBox(height: 15.0),
_image == null ? Text("No Image Selected") : Image.file(_image),
ElevatedButton.icon(
onPressed: () {
getImage;
print('camera'); // test
},
icon: const Icon(Icons.camera_alt_rounded),
label: const Text('Scan'),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green[500]),
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 22)),
)
)
]
),
),
);
}
}
另外,我應該嘗試改變
_image == 空?文本(“未選擇影像”):Image.file(_image),
線在更合適的地方還是可以像這樣嵌套?你對我的代碼還有什么其他意見嗎?
uj5u.com熱心網友回復:
試試這個
ElevatedButton.icon(
onPressed: getImage, // here need to change
icon: const Icon(Icons.camera_alt_rounded),
label: const Text('Scan'),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green[500]),
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 22)),
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340065.html
