如何解决bulding小部件时如何控制null
你能告诉我如何在下一页中包含 Image.file 的条件吗?我只想在 controller.image 为 not null 时构建它。
我遇到了一个错误: 在构建容器时抛出了以下 NoSuchMethodError(padding: EdgeInsets.all(32.0)): 方法 '[]' 在 null 上被调用。 接收器:空 尝试调用:
当我第一次重定向到这个页面时(并且 controller.image 为空):
class HomePage extends GetView<HomeController> {
final myController1 = TextEditingController();
final myController2 = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Grobonet'),),body: Padding(
padding: const EdgeInsets.all(16.0),child: Column(
children: <Widget>[
TextField(
controller: myController1,decoration: InputDecoration(
border: InputBorder.none,hintText: 'Nazwisko'),TextField(
controller: myController2,hintText: 'Miejscowosc'),IconButton(
icon: Icon(
Icons.add,size: 30,onPressed: () =>
Get.toNamed(
AppRoutes.PICK_IMAGE
),color: Colors.pink,IconButton(
icon: Icon(
Icons.save_outlined,/*onPressed: () =>
Get.toNamed(
AppRoutes.PICK_IMAGE
),*/
color: Colors.pink,Container(
padding: EdgeInsets.all(32),child: GetBuilder<HomeController>(
builder: (_) {
return Image.file(controller.image);
},]
),);
}
}
控制器:
class HomeController extends GetxController {
final image = Get.arguments['image'];
final file_loaded = Get.arguments['file_loaded'];
}
解决方法
您可以使用 collection-if。只需像这样添加 if (controller.image != null)
:
if (controller?.image != null)
Container(
padding: EdgeInsets.all(32),child: GetBuilder<HomeController>(
builder: (_) {
return Image.file(controller.image);
},),
,
在控制器的 onInit() 方法上使用获取您的参数:
class HomeController extends GetxController {
final File image;
final File file_loaded;
onInit(){
image = Get.arguments['image'];
file_loaded = Get.arguments['file_loaded'];
}
}
这样,除了 Get.arguments
实际上为 null 外,您不需要执行额外的 null 检查。
更新 而且您还需要像这样更新您的视图:
Container(
padding: EdgeInsets.all(32),child: GetBuilder<HomeController>(
builder: (_) {
return Image.file(_.image); // not return Image.file(controller.image);
// _ here is the instance of HomeController given by the GetBuilder
},
更新 2
正如您在评论中提到的,您希望将数据从第二个页面 (OCRDetailsPage) 发送到先前打开的页面 (HomePage)。那么你不需要传递参数。您可以使用 Get.find()
在 OCRDetailsPage 中获取 HomeController 实例并设置变量并更新状态,例如:
class OCRDetailsPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final OCRDetailsController controller = Get.find();
return Scaffold(
appBar: AppBar(title: Text('OCR Details Page')),body: Center(
child: FlatButton(
color: Colors.blue,child: Icon(Icons.save_outlined),onPressed: () {
final HomeController homeController = Get.find();
homeController.ocr_text = controller.text;
homeController.update();
Get.toNamed(
AppRoutes.HOME,);
}),);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。