必须初始化不可为空的实例字段“_selectedSize”
Posted
技术标签:
【中文标题】必须初始化不可为空的实例字段“_selectedSize”【英文标题】:Non-nullable instance field '_selectedSize' must be initialized 【发布时间】:2021-09-14 16:15:38 【问题描述】:我一直在使用我的 Store 应用程序,但现在这种零安全性让我很生气。我创建了一个类,但它给了我这个错误,后来不允许我的应用程序正常工作 这是 product.dart 文件:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:loja_virtual_nnananene/models/item_size.dart';
class Product extends ChangeNotifier
Product.fromDocument(DocumentSnapshot document)
id = document.documentID;
name = document['name'];
description = document['description'];
images = List<String>.from(document.data['images'] as List<dynamic>);
// ingore_for_file: Warning: Operand of null-aware operation
sizes = (document.data['sizes'] as List<dynamic> ?? [])
.map((s) => ItemSize.fromMap(s as Map<String, dynamic>))
.toList();
String id = "";
String name = "";
String description = "";
List<String> images = [];
List<ItemSize> sizes = [];
ItemSize _selectedSize;
ItemSize get selectedSize => _selectedSize;
set selectedSize(ItemSize value)
_selectedSize = value;
notifyListeners();
我在 Product.from 处收到错误消息... 这是错误:
Non-nullable instance field '_selectedSize' must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.
这是我的 ItemSize 类:
class ItemSize
ItemSize.fromMap(Map<String, dynamic> map)
name = map['name'] as String;
price = map['price'] as num;
stock = map['stock'] as int;
String name = "";
num price = 0;
int stock = 0;
bool get hasStock => stock > 0;
@override
String toString()
return 'ItemSizename: $name, price: $price, stock: $stock';
在主小部件中调用:
class SizeWidget extends StatelessWidget
const SizeWidget(this.size);
final ItemSize size;
@override
Widget build(BuildContext context)
final product = context.watch<Product>();
final selected = size == product.selectedSize;
Color color;
if (!size.hasStock)
color = Colors.red.withAlpha(50);
else if (selected)
color = ColorSelect.cprice;
【问题讨论】:
你没有调用 selectedSize,所以你没有初始化 _selectedSize 并且它保持为空 在我的主小部件中,我称之为,我已经更新了答案 你确定吗?在这里,您正在检查它是否等于size
并且您没有设置变量
但是那个问题,我试了设置还是不行,请问有什么tips
我尝试初始化为ItemSize _selectedSize = ItemSize as ItemSize
并尝试ItemSize _selectedSize = []
但没有成功
【参考方案1】:
代码第一次尝试获取选定的项目,当然它会为空。我找到的替代方案是......
在 ItemSize 类中,我创建了一个简单的构造函数,全部为 null -> ItemSize();
class ItemSize
ItemSize.fromMap(Map<String, dynamic> map)
name = map['name'] as String;
price = map['price'] as num;
stock = map['stock'] as int;
ItemSize();
String? name;
num? price;
int? stock;
bool get hasStock => stock! > 0;
@override
String toString()
return 'ItemSizename: $name, price: $price, stock: $stock';
在 Product 类中以这种方式获取。
ItemSize get selectedSize
if (_selectedSize != null)
return _selectedSize!;
else
return ItemSize();
【讨论】:
以上是关于必须初始化不可为空的实例字段“_selectedSize”的主要内容,如果未能解决你的问题,请参考以下文章
必须初始化不可为空的实例字段“_localizedStrings”