我在尝试使用照相机应用程序时遇到问题,即列的子代不能包含空值,但是在索引0处找到了空值。我无法在列的子代中传递小部件。
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() {
runApp(new MaterialApp(
title: "Camera App",
home: LandingScreen(),
));
}
class LandingScreen extends StatefulWidget {
@override
_LandingScreenState createState() => _LandingScreenState();
}
class _LandingScreenState extends State<LandingScreen> {
File imageFile;
_openGallery(BuildContext context) async {
var picture = await ImagePicker.pickImage(source: ImageSource.gallery);
this.setState((){
imageFile = picture;
});
Navigator.of(context).pop();
}
_openCamera(BuildContext context) async{
var picture = await ImagePicker.pickImage(source: ImageSource.camera);
this.setState((){
imageFile = picture;
});
Navigator.of(context).pop();
}
Future<void> _showChoiceDialog(BuildContext context){
return showDialog(context: context,builder: (BuildContext context){
return AlertDialog(
title: Text("Make a choice!"),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
GestureDetector(
child: Text("Gallery"),
onTap: (){
_openGallery(context);
},
),
Padding(padding: EdgeInsets.all(8.0),),
GestureDetector(
child: Text("Camera"),
onTap: (){
_openCamera(context);
},
),
],
),
),
);
});
}
Widget _decideImageView(){
if(imageFile == null){
return Text("No Image Selected");
}
else{
return Image.file(imageFile, width: 400, height: 400,);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Main Screen"),
),
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
_decideImageView(),
RaisedButton(onPressed: (){
_showChoiceDialog(context);
},child: Text("Select Image!"),)
],
)
)
)
);
}
}
我在else部分检查了是否返回,但是问题仍然存在。
我现在已经包括了整个代码。
答案 0 :(得分:2)
只需在_decideImageView()函数的else部分的Image.File之前添加一个返回值即可。
您必须记住,调用的函数_decideImageView()必须返回某些内容。因此,当您的imageFile不为null时,它将转到else而不返回。这就是为什么在列中出现空索引错误的原因
答案 1 :(得分:1)
在其他情况下,您必须返回Image Widget:
Widget _decideImageView(){
if(imageFile == null){
return Text("No Image Selected");
}
else{
return Image.file(imageFile, width: 400, height: 400,);
}
}