[英]How to solve Flutter error Column's children must not contain any null values, but a null value was found at index 0?
[英]Flutter error Column's children must not contain any null values, but a null value was found at index 0
我在 flutter 中尝试了一个相机应用程序,并遇到了列的子级不能包含 null 值的问题,但是在索引 0 处发现了 null 值。我无法通过列中的小部件子级。
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 部分检查了有无返回,但问题仍然存在。
我现在已经包含了整个代码。
在其他情况下,您必须返回您的图像小部件:
Widget _decideImageView(){
if(imageFile == null){
return Text("No Image Selected");
}
else{
return Image.file(imageFile, width: 400, height: 400,);
}
}
只需在 _decideImageView() function 的 else 部分的 Image.File 之前添加一个返回。
您必须记住,您调用的 function _decideImageView() 必须返回一些东西。 因此,当您的 imageFile 不是 null 时,它会转到 else 但不会返回。 这就是为什么您在列中收到 null 索引错误的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.