【发布时间】: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 'ItemSize{name: $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 = []但没有成功
标签: flutter null dart-null-safety