我使用https://pub.dev/packages/localstorage在Flutter应用中创建本地存储。我在“事件”小部件中创建了一些用于此本地存储的方法
class Event extends StatefulWidget {
final eventInfo;
Event({Key key, List eventInfo})
: this.eventInfo = eventInfo,
super(key: key);
@override
_EventState createState() => _EventState();
}
class FavName {
String eventName;
FavName({this.eventName});
get favEventName {
return eventName;
}
toJSONEncodable() {
Map<String, dynamic> m = new Map();
m['Name'] = eventName;
return m;
}
}
class FavList {
List<FavName> favNameList;
FavList() {
favNameList = new List();
}
toJSONEncodable() {
return favNameList.map((item) {
return item.toJSONEncodable();
}).toList();
}
}
class _EventState extends State<Event> {
final FavList list = new FavList();
final LocalStorage storage = new LocalStorage('favList');
addItem(String eventName) {
setState(() {
final item = new FavName(eventName: eventName);
list.favNameList.add(item);
_saveToStorage();
});
}
deleteItem(String eventName) {
setState(() {
final item = new FavName(eventName: eventName);
list.favNameList.remove(item);
_saveToStorage();
});
}
_saveToStorage() {
storage.setItem('favList', list.toJSONEncodable());
}
. . .
所以我想通过按钮将字符串添加到本地存储中。这是我的按钮代码。
child: IconButton(
icon: Icon(
Icons.star,
color: _iconColors,
),
onPressed: () {
print(name);
(storage.getItem(name)) ? deleteItem(name)
: addItem(name);
setState(() {
if (storage.getItem(name) == null) {
_iconColors = Colors.grey;
} else {
_iconColors = Colors.yellow;
}
});
})
但是当我点击按钮时,出现此错误
I/flutter (27489): 2-Art Event //Print the string that I want to add to the local storage
════════ Exception caught by gesture ═══════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Failed assertion: boolean expression must not be null
When the exception was thrown, this was the stack
#0 _EventState.buildInfo.<anonymous closure>
package:lx_building/screens/event.dart:190
#1 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:772
#2 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:855
#3 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:182
#4 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:522
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#1f697
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(324.7, 264.3)
finalLocalPosition: Offset(32.4, 9.7)
button: 1
sent tap down
════════════════════════════════════════════════════════════════════════════════
我该如何解决?
[storage.getItem(name)
返回存储的数据,通常是Map
。
在您的情况下,您必须使用布尔值。您可以测试返回的内容不为null:
(storage.getItem(name) != null) ? deleteItem(name)
: addItem(name);