Flutter: version 0.2.8 breaks code that used to work - flutter

Before I update to the new version of flutter (see below) everything worked OK.
Now it does no longer work.
The following piece of code performs a "paged" load of a gridView
Could somebody tell me what has changed with the last version of Flutter and how to solve this issue ?
Many thanks
Flutter version:
flutter --version
Flutter 0.2.8 • channel beta • https://github.com/flutter/flutter.git
Framework • revision b397406561 (11 days ago) • 2018-04-02 13:53:20 -0700
Engine • revision c903c217a1
Tools • Dart 2.0.0-dev.43.0.flutter-52afcba357
Here is the code that used to work:
typedef Future<PageAnswer> ApiPageRequest(int page, int pageSize);
class MIDApi {
///
/// Returns the list of items belonging to the active profile
///
Future<PageAnswer> getItems({
int pageIndex: 0,
int pageSize: 50,
#required String sortOrder
}) async {
String url = "ItemsList/$sortOrder";
return ajaxGet(url).then((String responseBody) async {
// print(responseBody);
final Map response = json.decode(responseBody);
final _status = response["status"];
if (_status == "OK"){
// Everything is OK
Map map = json.decode(response["data"]);
List<Map> objects = map["List"];
int total = map["Total"];
return new PageAnswer(objects, total);
}
return Null;
}).catchError((){
return Null;
});
}
}
///
/// This widget is used to display a "paged" GridView
///
/// Invocation example:
/// new PagedGridView<Map>(request, widgetAdapter: adapt);
///
/// where: request could be
/// Future<List<Map>> request(int page, int pageSize) async {
/// routine to fetch the data from the server
/// }
///
/// and adapt could be:
/// Widget adapt(Map map){
/// return new MyWidget(map);
/// }
///
class PagedGridView extends StatefulWidget {
/// Abstraction for loading the data.
/// This can be anything: An API-Call,
/// loading data from a certain file or database,
/// etc. If will deliver a list of objects (of type T)
final ApiPageRequest pageRequest;
/// The number of columns per row of the grid
final int numberColumns;
/// The number of elements requested for each page
final int pageSize;
/// The number of left-over elements in list which
/// will trigger loading the next page
final int pageThreshold;
/// Used for building Widgets out of the fetched data
final WidgetAdapter<Map> widgetAdapter;
final bool reverse;
final Indexer<Map> indexer;
final Stream<Map> topStream;
/// Constructor
const PagedGridView({
Key key,
this.numberColumns: 2,
this.pageSize: 50,
this.pageThreshold: 10,
#required this.pageRequest,
#required this.widgetAdapter,
this.reverse: false,
this.indexer,
this.topStream
}): super(key: key);
#override
State<StatefulWidget> createState() {
return new PagedGridViewState();
}
}
class PagedGridViewState extends State<PagedGridView> {
/// Contains all fetched elements ready to display
List<Map> objects = [];
/// Total number of objects that could be returned
int total = -1;
/// A Future returned by loadNext() if there
/// is currently a request running
/// or null, if no request is performed
Future request;
Map<int, int> index = {};
void doSomething(){
print("I need to do something");
}
void Clear() async {
await onRefresh();
}
#override
void initState(){
super.initState();
/// At start, let's systematically try to fetch some data
this.lockedLoadNext();
if (widget.topStream != null){
widget.topStream.listen((Map t){
setState((){
this.objects.insert(0, t);
this.reIndex();
});
});
}
}
#override
Widget build(BuildContext context){
GridView listView = new GridView.builder(
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: widget.numberColumns),
itemBuilder: itemBuilder,
itemCount: objects.length,
reverse: widget.reverse
);
RefreshIndicator refreshIndicator = new RefreshIndicator(
onRefresh: onRefresh,
child: listView
);
return new NotificationListener<ListElementUpdate<Map>>(
child: refreshIndicator,
onNotification: onUpdate
);
}
Widget itemBuilder(BuildContext context, int index){
/// If we are entering the threshold zone,
/// try to fetch additional objects
if (index + widget.pageThreshold > objects.length){
notifyThreshold();
}
return widget.widgetAdapter != null ? widget.widgetAdapter(objects[index])
: new Container();
}
void notifyThreshold(){
lockedLoadNext();
}
bool onUpdate(ListElementUpdate<Map> update){
if (widget.indexer == null){
debugPrint('ListElementUpdate on un-indexed list');
return false;
}
int index = this.index[update.key];
if (index == null){
debugPrint('ListElementUpdate index not found');
return false;
}
setState((){
this.objects[index] = update.instance;
});
return true;
}
Future onRefresh() async {
this.request?.timeout(const Duration());
PageAnswer answer = await widget.pageRequest(0, widget.pageSize);
List<Map> fetched = answer.list;
total = answer.total;
setState(() {
this.objects.clear();
this.index.clear();
this.addObjects(fetched);
});
return true;
}
///
/// This routine only fetches new data, if no other request is pending
///
void lockedLoadNext() {
if (this.request == null) {
this.request = loadNext().then((x) {
this.request = null;
});
}
}
Future loadNext() async {
// If there is no need to fetch any further data, simply return
if (objects.length >= total && total != -1){
return Null;
}
int page = (objects.length / widget.pageSize).floor();
PageAnswer answer = await widget.pageRequest(page, widget.pageSize);
List<Map> fetched = answer.list;
total = answer.total;
if (mounted) {
this.setState(() {
addObjects(fetched);
});
}
}
void addObjects(Iterable<Map> objects) {
objects.forEach((Map object) {
int index = this.objects.length;
this.objects.add(object);
if (widget.indexer != null) {
this.index[widget.indexer(object)] = index;
}
});
}
void reIndex(){
this.index .clear();
if (widget.indexer!=null){
int i = 0;
this.objects.forEach((object){
index[widget.indexer(object)] == i;
i++;
});
}
}
}
Invocation code:
class ItemsPage extends StatefulWidget {
#override
_ItemsPageState createState() => new _ItemsPageState();
}
class _ItemsPageState extends State<ItemsPage> {
static final GlobalKey<PagedGridViewState> _gridKey = new GlobalKey<PagedGridViewState>();
String _path = mid.serverHttps ? "https://${mid.serverUrl}/"
: "http://${mid.serverUrl}/";
String _sortOrder;
final List<SortMethod> sortMethods = const <SortMethod>[
const SortMethod(value: 'alpha', title: "Alpha", icon: Icons.sort_by_alpha),
const SortMethod(value: 'older_first', title: "Older first", icon: Icons.autorenew),
const SortMethod(value: 'last_first', title: "Last first", icon: Icons.change_history),
];
Future<PageAnswer> request(int page, int pageSize) async {
PageAnswer answer = await mid.api.getItems(sortOrder: _sortOrder);
return answer;
}
void _handleTap(int lookId) {
print('tap:' + lookId.toString());
}
Widget adapt(Map map){
var photos = map["Photos"].split(";");
String photoName = photos[0].split("|")[0];
return new GestureDetector(
onTap: () {_handleTap(map["Id"]);},
child: new GridTile(
child: new Card(
child: new Stack(
fit: StackFit.expand,
children: <Widget>[
new Image.network(_path + photoName,
fit: BoxFit.fitHeight),
new Center(
child: new Text(
map["Title"],
textAlign: TextAlign.center,
)),
],
),
),
),
);
}
_onSortOrderChanged(String value) {
setState((){
_sortOrder = value;
_gridKey.currentState.Clear();
});
}
#override
void initState(){
super.initState();
_sortOrder = 'alpha';
}
#override
Widget build(BuildContext context) {
PagedGridView grid = new PagedGridView(
key: _gridKey,
pageRequest: request,
widgetAdapter: adapt,
numberColumns: 2,
);
DropdownButton ddl = new DropdownButton<String>(
value: _sortOrder,
items: sortMethods.map((SortMethod sort){
return new DropdownMenuItem(
value: sort.value,
child: new Row(children: <Widget>[new Icon(sort.icon), new Text(sort.title)],)
);
}).toList(),
onChanged: _onSortOrderChanged,
);
PopupMenuButton<ItemSorting> popSort = new PopupMenuButton<ItemSorting>(
icon: new Icon(Icons.sort),
itemBuilder: (BuildContext context) => <PopupMenuItem<ItemSorting>> [
const PopupMenuItem<ItemSorting>(
value: ItemSorting.alpha,
child: const Text('Sort Alpha')
),
const PopupMenuItem<ItemSorting>(
value: ItemSorting.last_first,
child: const Text('Sort Last First')
),
const PopupMenuItem<ItemSorting>(
value: ItemSorting.older_first,
child: const Text('Sort Older First')
)
],
onSelected: (ItemSorting action){
_onSortOrderChanged(action.toString().split('.')[1]);
},
);
return new Scaffold(
appBar: new AppBar(
title: new Text('My Items'),
actions: <Widget>[
popSort, //ddl,
],
),
body: new Center(
child: grid,
),
);
}
}
class SortMethod {
const SortMethod({this.title, this.icon, this.value});
final String title;
final IconData icon;
final String value;
}
Error stack:
E/flutter (15195): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (15195): type 'Future<Object>' is not a subtype of type 'FutureOr<PageAnswer>' where
E/flutter (15195): Future is from dart:async
E/flutter (15195): Object is from dart:core
E/flutter (15195): FutureOr is from dart:async
E/flutter (15195): PageAnswer is from file:///D:/Development/appli/lib/libraries/function_types.dart
E/flutter (15195):
E/flutter (15195): #0 MIDApi.getItems (file:///D:/Development/appli/lib/libraries/api.dart:35:8)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #1 _ItemsPageState.request (file:///D:/Development/appli/lib/pages/items.dart:30:39)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #2 PagedGridViewState.loadNext (file:///D:/Development/appli/lib/widgets/paged_grid_view.dart:191:38)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #3 PagedGridViewState.lockedLoadNext (file:///D:/Development/appli/lib/widgets/paged_grid_view.dart:178:22)
E/flutter (15195): #4 PagedGridViewState.initState (file:///D:/Development/appli/lib/widgets/paged_grid_view.dart:93:10)
E/flutter (15195): #5 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3734:58)
E/flutter (15195): #6 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
E/flutter (15195): #7 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter (15195): #8 Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter (15195): #9 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4637:14)
E/flutter (15195): #10 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter (15195): #11 Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter (15195): #12 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3636:16)
E/flutter (15195): #13 Element.rebuild (package:flutter/src/widgets/framework.dart:3478:5)
E/flutter (15195): #14 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3605:5)
E/flutter (15195): #15 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
E/flutter (15195): #16 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter (15195): #17 Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter (15195): #18 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3636:16)
E/flutter (15195): #19 Element.rebuild (package:flutter/src/widgets/framework.dart:3478:5)
E/flutter (15195): #20 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3605:5)
E/flutter (15195): #21 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
E/flutter (15195): #22 ParentDataElement.mount (package:flutter/src/widgets/framework.dart:3938:11)
E/flutter (15195): #23 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter (15195): #24 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4742:32)
E/flutter (15195): #25 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter (15195): #26 Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter (15195): #27 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3636:16)
E/flutter (15195): #28 Element.rebuild (package:flutter/src/widgets/framework.dart:3478:5)
E/flutter (15195): #29 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3605:5)
E/flutter (15195): #30 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3752:11)
E/flutter (15195): #31 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
E/flutter (15195): #32 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter (15195): #33 Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter (15195): #34 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3636:16)
E/flutter (15195): #35 Element.rebuild (package:flutter/src/widgets/framework.dart:3478:5)
E/flutter (15195): #36 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3605:5)
E/flutter (15195): #37 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
E/flutter (15195): #38 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter (15195): #39 Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter (15195): #40 ComponentElement.performRebuild (packag
E/flutter (15195): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (15195): type 'Future<Object>' is not a subtype of type 'FutureOr<PageAnswer>' where
E/flutter (15195): Future is from dart:async
E/flutter (15195): Object is from dart:core
E/flutter (15195): FutureOr is from dart:async
E/flutter (15195): PageAnswer is from file:///D:/Development/appli/lib/libraries/function_types.dart
E/flutter (15195):
E/flutter (15195): #0 MIDApi.getItems (file:///D:/Development/appli/lib/libraries/api.dart:34:8)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #1 _ItemsPageState.request (file:///D:/Development/appli/lib/pages/items.dart:30:39)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #2 PagedGridViewState.onRefresh (file:///D:/Development/appli/lib/widgets/paged_grid_view.dart:160:38)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #3 PagedGridViewState.Clear (file:///D:/Development/appli/lib/widgets/paged_grid_view.dart:85:11)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #4 _ItemsPageState._onSortOrderChanged.<anonymous closure> (file:///D:/Development/appli/lib/pages/items.dart:67:29)
E/flutter (15195): #5 State.setState (package:flutter/src/widgets/framework.dart:1108:30)
E/flutter (15195): #6 _ItemsPageState._onSortOrderChanged (file:///D:/Development/appli/lib/pages/items.dart:65:5)
E/flutter (15195): #7 _ItemsPageState.build.<anonymous closure> (file:///D:/Development/appli/lib/pages/items.dart:114:9)
E/flutter (15195): #8 _PopupMenuButtonState.showButtonMenu.<anonymous closure> (package:flutter/src/material/popup_menu.dart)
E/flutter (15195): #9 _RootZone.runUnary (dart:async/zone.dart:1381:54)
E/flutter (15195): #10 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter (15195): #11 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
E/flutter (15195): #12 Future._propagateToListeners (dart:async/future_impl.dart:662:32)
E/flutter (15195): #13 Future._completeWithValue (dart:async/future_impl.dart:477:5)
E/flutter (15195): #14 Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:507:7)
E/flutter (15195): #15 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter (15195): #16 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
I/flutter (15195): Another exception was thrown: type '() => Future<dynamic>' is not a subtype of type '() => Future<Null>'
E/flutter (15195): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (15195): type '() => Type' is not a subtype of type '(Object) => FutureOr<Object>'
E/flutter (15195): #0 _FutureListener.handleError (dart:async/future_impl.dart:145:11)
E/flutter (15195): #1 Future._propagateToListeners.handleError (dart:async/future_impl.dart:645:47)
E/flutter (15195): #2 Future._propagateToListeners (dart:async/future_impl.dart:666:24)
E/flutter (15195): #3 Future._completeError (dart:async/future_impl.dart:485:5)
E/flutter (15195): #4 _SyncCompleter._completeError (dart:async/future_impl.dart:55:12)
E/flutter (15195): #5 _Completer.completeError (dart:async/future_impl.dart:27:5)
E/flutter (15195): #6 MIDApi.getItems.<anonymous closure> (file:///D:/Development/appli/lib/libraries/api.dart)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #7 _RootZone.runUnary (dart:async/zone.dart:1381:54)
E/flutter (15195): #8 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter (15195): #9 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
E/flutter (15195): #10 Future._propagateToListeners (dart:async/future_impl.dart:662:32)
E/flutter (15195): #11 Future._complete (dart:async/future_impl.dart:467:7)
E/flutter (15195): #12 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter (15195): #13 ajaxGet (file:///D:/Development/appli/lib/libraries/ajax.dart)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #14 MIDApi.getItems (file:///D:/Development/appli/lib/libraries/api.dart:21:12)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #15 _ItemsPageState.request (file:///D:/Development/appli/lib/pages/items.dart:30:39)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #16 PagedGridViewState.onRefresh (file:///D:/Development/appli/lib/widgets/paged_grid_view.dart:160:38)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #17 PagedGridViewState.Clear (file:///D:/Development/appli/lib/widgets/paged_grid_view.dart:85:11)
E/flutter (15195): <asynchronous suspension>
E/flutter (15195): #18 _ItemsPageState._onSortOrderChanged.<anonymous closure> (file:///D:/Development/appli/lib/pages/items.dart:67:29)
E/flutter (15195): #19 State.setState (package:flutter/src/widgets/framework.dart:1108:30)
E/flutter (15195): #20 _ItemsPageState._onSortOrderChanged (file:///D:/Development/appli/lib/pages/items.dart:65:5)
E/flutter (15195): #21 _ItemsPageState.build.<anonymous closure> (file:///D:/Development/appli/lib/pages/items.dart:114:9)
E/flutter (15195): #22 _PopupMenuButtonState.showButtonMenu.<anonymous closure> (package:flutter/src/material/popup_menu.dart)
E/flutter (15195): #23 _RootZone.runUnary (dart:async/zone.dart:1381:54)
E/flutter (15195): #24 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter (15195): #25 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
E/flutter (15195): #26 Future._propagateToListeners (dart:async/future_impl.dart:662:32)
E/flutter (15195): #27 Future._completeWithValue (dart:async/future_impl.dart:477:5)
E/flutter (15195): #28 Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:507:7)
E/flutter (15195): #29 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter (15195): #30 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)

Related

Audio Service How to retrieve a variable with a StateFul widget

For my project I use the packages audioplayers for my audio sound and I need to use the sound in background and to control it with the notification and for that I use the package audio_service and now I have a problem.
First of all I want to precise I use this class to retrieve the song and others variables from an other page.
class MyPlayerController extends StatefulWidget {
final Song songToPlay;
final List<Song> playlist;
final Color backgroundColor;
const MyPlayerController({required this.songToPlay, required this.playlist, required this.backgroundColor});
#override
AudioPlayerHandler createState() => AudioPlayerHandler();
}
Now I declare all of this to control my audio player :
class AudioPlayerHandler extends BaseAudioHandler with State<MyPlayerController>,Diagnosticable{
late AudioHandler audioHandler;
late AudioPlayer audioPlayer;
late Song song;
AudioCache? audioCache;
double soundMax = 1;
double soundPosition = 0.5;
Duration position = const Duration(seconds: 0);
Duration maxDuration = const Duration(seconds: 0);
bool playShuffle = false;
bool repeat = false;
IconData iconData = Icons.play_circle;
#override
void initState() {
super.initState();
}
#override
void dispose() {
clearPlayer();
super.dispose();
}
#override
Future<void> play() async {
playbackState.add(playbackState.value.copyWith(
playing: true,
controls: [MediaControl.pause],
));
await setupPlayer();
}
#override
Future<void> pause() async {
playbackState.add(playbackState.value.copyWith(
playing: false,
controls: [MediaControl.play],
));
await audioPlayer.pause();
}
After that when i call the setupPlayer
setupPlayer() {
song = widget.songToPlay;
audioPlayer = AudioPlayer();
audioPlayer.onPlayerStateChanged.listen(onStateChange);
audioPlayer.onDurationChanged.listen(onDurationChange);
audioPlayer.onAudioPositionChanged.listen(onAudioPositionChanged);
final url = song.path;
audioPlayer.play(url);
//changeVolume(soundPosition);
}
That made me this error
E/flutter (10633): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter (10633): #0 State.widget (package:flutter/src/widgets/framework.dart:916:26)
E/flutter (10633): #1 AudioPlayerHandler.setupPlayer (package:easyislam/view/spotify/controllers/player_controller.dart:190:12)
E/flutter (10633): #2 AudioPlayerHandler.play (package:easyislam/view/spotify/controllers/player_controller.dart:233:11)
E/flutter (10633): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
E/flutter (10633): #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
E/flutter (10633): #5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
E/flutter (10633): #6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
E/flutter (10633): #7 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
E/flutter (10633): #8 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:563:9)
E/flutter (10633): #9 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
E/flutter (10633): #10 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:139:9)
E/flutter (10633): #11 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
E/flutter (10633): #12 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
E/flutter (10633): #13 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
E/flutter (10633): #14 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
E/flutter (10633): #15 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter (10633): #16 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
E/flutter (10633): #17 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter (10633): #18 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter (10633): #19 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter (10633): #20 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter (10633): #21 _rootRunUnary (dart:async/zone.dart:1442:13)
E/flutter (10633): #22 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter (10633): #23 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter (10633): #24 _invoke1 (dart:ui/hooks.dart:170:10)
E/flutter (10633): #25 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
E/flutter (10633): #26 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
I tried to retrieve the song with a setState :
setState(() {
song = widget.songToPlay;
});
audioPlayer = AudioPlayer();
audioPlayer.onPlayerStateChanged.listen(onStateChange);
audioPlayer.onDurationChanged.listen(onDurationChange);
audioPlayer.onAudioPositionChanged.listen(onAudioPositionChanged);
final url = song.path;
audioPlayer.play(url);
//changeVolume(soundPosition);
}
And that made me this error :
E/flutter (10633): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: setState() called in constructor: AudioPlayerHandler#ee85b
E/flutter (10633): This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created.
E/flutter (10633): #0 State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1109:9)
E/flutter (10633): #1 State.setState (package:flutter/src/widgets/framework.dart:1120:6)
E/flutter (10633): #2 AudioPlayerHandler.setupPlayer (package:easyislam/view/spotify/controllers/player_controller.dart:190:5)
E/flutter (10633): #3 AudioPlayerHandler.play (package:easyislam/view/spotify/controllers/player_controller.dart:236:11)
E/flutter (10633): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
E/flutter (10633): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
E/flutter (10633): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
E/flutter (10633): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
E/flutter (10633): #8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
E/flutter (10633): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:563:9)
E/flutter (10633): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
E/flutter (10633): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:139:9)
E/flutter (10633): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
E/flutter (10633): #13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
E/flutter (10633): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
E/flutter (10633): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
E/flutter (10633): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter (10633): #17 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
E/flutter (10633): #18 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter (10633): #19 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter (10633): #20 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter (10633): #21 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter (10633): #22 _rootRunUnary (dart:async/zone.dart:1442:13)
E/flutter (10633): #23 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter (10633): #24 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter (10633): #25 _invoke1 (dart:ui/hooks.dart:170:10)
E/flutter (10633): #26 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
E/flutter (10633): #27 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
I use this packages :
import 'package:audio_service/audio_service.dart';
import 'package:audioplayers/audioplayers.dart';
I want to know how I can retrieve this song without this error.

How to execute write method in function that changes value in slidebar?

When the slide bar value changes, it tries to write a packet.
I am using the example,
I made a function and tried it, but a null error occurs. (discoverService, characteristic.., etc.)
How can I solve this?
I'm using flutter_blue
In the flutter_blue example, write works fine.
I'm flutter beginer.
I need your help. thank you.
https://pub.dev/packages/flutter_blue
onWriteData
var data = [0x80, 0x80, 0xF0, 0x7D, 0x05, 0x00, 0x0E, 0x01, 60, 100, 00,0x80, 0xF7];
FlutterBlue flutterBlue = FlutterBlue.instance;
BluetoothDevice device;
BluetoothService service;
onWriteData() async {
List<BluetoothService> services = await device.discoverServices();
services.forEach((service) {
});
var characteristics = service.characteristics;
for(BluetoothCharacteristic c in characteristics) {
List<int> value = await c.read();
print(value);
await c.write(data);
}
}
slideBar class
class slidecontrollerr extends State<slidecontroller> {
static double volumeValue = 60;
void onVolumeChanged(double value) async { **// I want to execute the write function here**
setState(() {
volumeValue = value;
});
onWriteData(); **//error**
}
#override
Widget build(BuildContext context) {
return Scaffold(
.
.
.
[Error Code][1]
E/flutter ( 5640): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The method 'discoverServices' was called on null.
E/flutter ( 5640): Receiver: null
E/flutter ( 5640): Tried calling: discoverServices()
E/flutter ( 5640): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter ( 5640): #1 onWriteData (package:auto_humidity/main.dart:467:48)
E/flutter ( 5640): #2 slidecontrollerr.onVolumeChanged (package:auto_humidity/main.dart:1489:5)
E/flutter ( 5640): #3 RenderRadialAxisParent.createPointerValueChangedArgs (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:584:43)
E/flutter ( 5640): #4 RenderRadialAxisParent._setCurrentPointerValue (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:548:5)
E/flutter ( 5640): #5 RenderRadialAxisParent._updateDragValue (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:527:7)
E/flutter ( 5640): #6 RenderRadialAxisParent._updatePointerValue (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:452:7)
E/flutter ( 5640): #7 RenderRadialAxisParent._handleDragUpdate (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:339:5)
E/flutter ( 5640): #8 DragGestureRecognizer._checkUpdate.<anonymous closure> (package:flutter/src/gestures/monodrag.dart:436:55)
E/flutter ( 5640): #9 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter ( 5640): #10 DragGestureRecognizer._checkUpdate (package:flutter/src/gestures/monodrag.dart:436:7)
E/flutter ( 5640): #11 DragGestureRecognizer.handleEvent (package:flutter/src/gestures/monodrag.dart:289:9)
E/flutter ( 5640): #12 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:93:12)
E/flutter ( 5640): #13 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:138:9)
E/flutter ( 5640): #14 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter ( 5640): #15 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:136:18)
E/flutter ( 5640): #16 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:122:7)
E/flutter ( 5640): #17 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
E/flutter ( 5640): #18 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter ( 5640): #19 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:287:11)
E/flutter ( 5640): #20 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter ( 5640): #21 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter ( 5640): #22 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter ( 5640): #23 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter ( 5640): #24 _rootRunUnary (dart:async/zone.dart:1370:13)
E/flutter ( 5640): #25 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 5640): #26 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter ( 5640): #27 _invoke1 (dart:ui/hooks.dart:182:10)
E/flutter ( 5640): #28 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:282:7)
E/flutter ( 5640): #29 _dispatchPointerDataPacket (dart:ui/hooks.dart:96:31)
You need to connect to a specific service and characteristics of your BLE device
Here is a piece of code that I am using
final String serviceUUID = "0000ffe0-0000-1000-8000-00805f9b34fb";
final String characteristicWriteUUID = "0000fff1-0000-1000-8000-00805f9b34fb";
final String characteristicReadUUID = "0000fff2-0000-1000-8000-00805f9b34fb";
These services and characteristics must be set in the module itself by default or by you manually
discoverServices(BluetoothDevice device) async {
if (device == null) return;
List<BluetoothService> services = await device.discoverServices();
services.forEach((service) {
// do something with service
if (service.uuid.toString().toLowerCase() == serviceUUID) {
service.characteristics.forEach((characteristic) {
if (characteristic.uuid.toString().toLowerCase() == characteristicReadUUID) {
targetReadCharacteristic = characteristic;
_readData(targetReadCharacteristic);
}
if (characteristic.uuid.toString().toLowerCase() == characteristicWriteUUID) {
targetWriteCharacteristic = characteristic;
writeData(targetWriteCharacteristic, [0x49, 0x44, 0x02]);
}
});
}
});
}
Future<void> writeData(characteristic, data) async{
if (characteristic == null) return;
try {
List<int> bytes = data;
await characteristic.write(bytes, withoutResponse: true );
print("data: Send: $data");
} catch (e) {
print('Data Error ${e.message} | $data');
}
}
_readData(characteristic) async {
if (!characteristic.isNotifying) {
await characteristic.setNotifyValue(true);
}
readSubScription = characteristic.value.listen((value) {
List<int> readData = new List.from(value);
if(readData.isNotEmpty && readData != []){
print('BLE read data: $readData');
}
});
}

NoSuchMethodError: The method '[]' was called on null. flutter local json file

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 8471): Receiver: null
E/flutter ( 8471): Tried calling: []("runnerId")
E/flutter ( 8471): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 8471): #1 new Metadata.fromMap (package:jsonfatch/model/event.dart:348:22)
E/flutter ( 8471): #2 new MarketRunner.fromMap (package:jsonfatch/model/event.dart:329:28)
E/flutter ( 8471): #3 new Market.fromMap.<anonymous closure> (package:jsonfatch/model/event.dart:138:52)
E/flutter ( 8471): #4 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
E/flutter ( 8471): #5 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
E/flutter ( 8471): #6 new List.from (dart:core-patch/array_patch.dart:57:19)
E/flutter ( 8471): #7 new Market.fromMap (package:jsonfatch/model/event.dart:137:18)
E/flutter ( 8471): #8 new EventDetails.fromMap.<anonymous closure> (package:jsonfatch/model/event.dart:65:62)
E/flutter ( 8471): #9 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
E/flutter ( 8471): #10 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
E/flutter ( 8471): #11 new List.from (dart:core-patch/array_patch.dart:57:19)
E/flutter ( 8471): #12 new EventDetails.fromMap (package:jsonfatch/model/event.dart:65:11)
E/flutter ( 8471): #13 HomePageState.loadData.<anonymous closure> (package:jsonfatch/home.dart:28:51)
E/flutter ( 8471): #14 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
E/flutter ( 8471): #15 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
E/flutter ( 8471): #16 new List.from (dart:core-patch/array_patch.dart:38:29)
E/flutter ( 8471): #17 new List.of (dart:core-patch/array_patch.dart:68:17)
E/flutter ( 8471): #18 ListIterable.toList (dart:_internal/iterable.dart:211:44)
E/flutter ( 8471): #19 HomePageState.loadData (package:jsonfatch/home.dart:29:10)
E/flutter ( 8471): <asynchronous suspension>
E/flutter ( 8471): #20 HomePageState.initState (package:jsonfatch/home.dart:19:5)
E/flutter ( 8471): #21 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4765:58)
E/flutter ( 8471): #22 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
E/flutter ( 8471): #23 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter ( 8471): #24 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter ( 8471): #25 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1252:16)
E/flutter ( 8471): #26 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1223:5)E/flutter ( 8471): #27 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1165:17)
E/flutter ( 8471): #28 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2683:19)
E/flutter ( 8471): #29 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1164:13)
E/flutter ( 8471): #30 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:974:7)
E/flutter ( 8471): #31 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:955:7)
E/flutter ( 8471): #32 _rootRun (dart:async/zone.dart:1182:47)
E/flutter ( 8471): #33 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 8471): #34 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 8471): #35 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter ( 8471): #36 _rootRun (dart:async/zone.dart:1190:13)
E/flutter ( 8471): #37 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 8471): #38 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter ( 8471): #39 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter ( 8471): #40 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter ( 8471): #41 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter ( 8471): #42 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
my json file in which the data is nested key value per and do many json obj
"runners":[
{
"id":10301,
"name":"roman",
"sortPriority":0,
"metadata":{
"runnerId":"10301"
}
},
{
"id":7337,
"name":"khali",
"sortPriority":0,
"metadata":{
"runnerId":"7337"
}
}
],
my map code for the runnerId. it was an nested array object. other all i have maped in model file
class Metadata {
Metadata({
this.runnerId,
});
String runnerId;
factory Metadata.fromMap(Map<String, dynamic> map) => Metadata(
runnerId: map["runnerId"],
);
Map<String, dynamic> toMap() => {
"runnerId": runnerId,
};
}
My Home.dart Code
class HomePage extends StatefulWidget {
#override
HomePageState createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
#override
void initState() {
super.initState();
loadData();
}
loadData() async {
await Future.delayed(Duration(seconds: 2));
var cktJson = await rootBundle.loadString("assets/files/ckt.json");
var decodedData = jsonDecode(cktJson);
var cricketData = decodedData["cktdata"];
EventsModel.markets = List.from(cricketData)
.map<EventDetails>((item) => EventDetails.fromMap(item))
.toList();
setState(() {});
print("Decoded :-"+decodedData);
print("CrircktD :-"+ cricketData);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
backgroundColor: MainBackgroundColor,
title: Text("Radhe Json Fatch"),
),
body: SafeArea(
child: Column(
children: [
Expanded(
child: (EventsModel.markets != null && EventsModel.markets.isNotEmpty)?
ListView.builder(
scrollDirection: Axis.vertical,
itemCount: EventsModel.markets.length,
itemBuilder: (context, index) {
return LiveEventCricket(item: EventsModel.markets[index]);
},
):Center(child: CircularProgressIndicator()),
),
],
),
),
),
);
}
}

Flutter & Ethereum : Unhandled Exception: RangeError: Value not in range: 32

I am trying to make a simple Decentralization Application with flutter and Ethereum. But I keep on getting this error. It was working fine. Please have a look at my code and my error
I use :
Flutter
Remix Ethereum
MetaMask => Rinkeby
Infua.io
Question : Why do I get this RangerError?
Solidity
pragma solidity 0.6.6;
contract PKCoin{
int balance;
constructor() public {
balance = 0;
}
function getBalance() view public returns(int) {
return balance;
}
function depositBalance(int amount) public {
balance = balance + amount;
}
function withdrawBalance(int amount) public {
balance = balance - amount;
}
}
Flutter
#override
void initState() {
super.initState();
httpClient = Client();
// print(httpClient);
ethClient = Web3Client(
"https://rinkeby.infura.io/v3/b2a9d5831e3b4675a51144cfed03bafa",
httpClient);
getBalance(myAddress);
}
Future<DeployedContract> loadContract() async {
String abi = await rootBundle.loadString("assets/abi.json");
String contractAddress = "0xd9145CCE52D386f254917e481eB44e9943F39138";
final contract = DeployedContract(ContractAbi.fromJson(abi, "PKCoin"),
EthereumAddress.fromHex(contractAddress));
return contract;
}
// ==== This is to get the information only ==== //
// ==== Get method ==== //
Future<List<dynamic>> query(String functionName, List<dynamic> args) async {
//
final contract = await loadContract();
final ethFunction = contract.function(functionName);
// This line below doesn't work.
final result = await ethClient.call(
contract: contract, function: ethFunction, params: args);
// print(result.toString());
return result;
}
Future<void> getBalance(String targetAddress) async {
// EthereumAddress address = EthereumAddress.fromHex(targetAddress);
List<dynamic> result = await query("getBalance", []);
print('In getGreeting');
print(result[0]);
setState(() {
myData = result[0];
data = true;
});
}
Error
Performing hot restart...
Restarted application in 950ms.
E/flutter (28032): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: RangeError: Value not in range: 32
E/flutter (28032): #0 _rangeCheck (dart:typed_data-patch/typed_data_patch.dart:4807:5)
E/flutter (28032): #1 _ByteBuffer.asUint8List (dart:typed_data-patch/typed_data_patch.dart:1940:5)
E/flutter (28032): #2 _IntTypeBase.decode (package:web3dart/src/contracts/abi/integers.dart:23:31)
E/flutter (28032): #3 TupleType.decode (package:web3dart/src/contracts/abi/tuple.dart:102:29)
E/flutter (28032): #4 ContractFunction.decodeReturnValues (package:web3dart/src/contracts/abi/abi.dart:255:30)
E/flutter (28032): #5 Web3Client.call (package:web3dart/src/core/client.dart:310:21)
E/flutter (28032): <asynchronous suspension>
E/flutter (28032): #6 _MyHomePageState.query (package:greeting_blockchain/main.dart:70:36)
E/flutter (28032): <asynchronous suspension>
E/flutter (28032): #7 _MyHomePageState.getBalance (package:greeting_blockchain/main.dart:79:34)
E/flutter (28032): #8 _MyHomePageState.initState (package:greeting_blockchain/main.dart:48:5)
E/flutter (28032): #9 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4765:58)
E/flutter (28032): #10 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
E/flutter (28032): #11 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter (28032): #12 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter (28032): #13 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6118:14)
E/flutter (28032): #14 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter (28032): #15 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter (28032): #16 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
E/flutter (28032): #17 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
E/flutter (28032): #18 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4606:5)
E/flutter (28032): #19 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
E/flutter (28032): #20 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter (28032): #21 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter (28032): #22 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6118:14)
E/flutter (28032): #23 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter (28032): #24 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter (28032): #25 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6118:14)
E/flutter (28032): #26 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter (28032): #27 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter (28032): #28 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
E/flutter (28032): #29 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
E/flutter (28032): #30 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
E/flutter (28032): #31 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4606:5)
E/flutter (28032): #32 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4791:11)
E/flutter (28032): #33 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
E/flutter (28032): #34 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter (28032): #35 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter (28032): #36 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6118:14)
E/flutter (28032): #37 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter (28032): #38 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter (28032): #39 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6118:14)
E/flutter (28032): #40 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter (28032): #41 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter (28032): #42 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
E/flutter (28032): #43 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
E/flutter (28032): #44 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
E/flutter (28032): #45 ComponentElement._firstBuild (package:flutter/src/widgets/framework.d
Conclusion
Please take a look at my code and I am looking forward to see all of your answers. Thank you in advance.
Un-comment //EthereumAddress address = EthereumAddress.fromHex(targetAddress);
Future<void> getBalance(String targetAddress) async {
EthereumAddress address = EthereumAddress.fromHex(targetAddress);
List<dynamic> result = await query("getBalance", []);
print('In getGreeting');
print(result[0]);
setState(() {
myData = result[0];
data = true;
});
}

Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null. Shared Preference

While fetching the data for the first time from shared preference, I am getting this error: Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null. But after the hot restart, I am getting the data as usual.
Retrieving data from Dashboard Screen
loadSharedPrefs() async {
var decodedData = await sharedPref.read("details");
signInItem = SignInItem.fromJson(decodedData);
setState(() {});
}
Saving data in SignIn screen
await FirebaseAuth.instance
.signInWithCredential(_phoneAuthCredential)
.then((AuthResult authRes) {
Navigator.pop(context);
Flushbar(
message: "Verified!!",
duration: Duration(seconds: 2),
)..show(context);
sharedPref.save("details", signInItem);
Navigator.popAndPushNamed(context, DashboardScreen.id);
});
Model Class
class SignInItem {
String phoneNumber;
String schoolCode;
String schoolReference;
Map<String, dynamic> teacherData;
String error;
SignInItem.fromJson(Map<String, dynamic> json)
: phoneNumber = json['phoneNumber'],
schoolCode = json['schoolCode'],
schoolReference = json['schoolReference'],
teacherData = json['teacherData'],
error = json['error'];
Map<String, dynamic> toJson() => {
'phoneNumber': phoneNumber,
'schoolCode': schoolCode,
'schoolReference': schoolReference,
'teacherData': teacherData,
'error': error,
};
SignInItem(
{this.phoneNumber,
this.schoolCode,
this.schoolReference,
this.teacherData,
this.error});
}
Shared preference helper class
class SharedPref {
read(String key) async {
final prefs = await SharedPreferences.getInstance();
return json.decode(prefs.getString(key));
}
save(String key, SignInItem signInItem) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, json.encode(signInItem.toJson()));
}
}
Detail Stacktrace
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null.
E/flutter (19241): Receiver: null
E/flutter (19241): Tried calling: length
E/flutter (19241): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter (19241): #1 _parseJson (dart:convert-patch/convert_patch.dart:39:28)
E/flutter (19241): #2 JsonDecoder.convert (dart:convert/json.dart:505:36)
E/flutter (19241): #3 JsonCodec.decode (dart:convert/json.dart:156:41)
E/flutter (19241): #4 SharedPref.read (package:teacher_app/constants.dart:156:17)
E/flutter (19241): <asynchronous suspension>
E/flutter (19241): #5 _DashboardScreenState.loadSharedPrefs (package:teacher_app/screens/dashboard_screen.dart:33:40)
E/flutter (19241): #6 _DashboardScreenState.initState (package:teacher_app/screens/dashboard_screen.dart:49:5)
E/flutter (19241): #7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4684:58)
E/flutter (19241): #8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
E/flutter (19241): #9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #10 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #11 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #12 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #13 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #14 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
E/flutter (19241): #15 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
E/flutter (19241): #16 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
E/flutter (19241): #17 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
E/flutter (19241): #18 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #19 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #20 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #21 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #22 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #23 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #24 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #25 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #26 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
E/flutter (19241): #27 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
E/flutter (19241): #28 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
E/flutter (19241): #29 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
E/flutter (19241): #30 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4710:11)
E/flutter (19241): #31 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
E/flutter (19241): #32 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #33 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #34 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #35 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #36 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #37 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #38 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #39 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #40 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
E/flutter (19241): #41 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
E/flutter (19241): #42 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
E/flutter (19241): #43 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
E/flutter (19241): #44 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4710:11)
E/flutter (19241): #45 ComponentElement.mount (package:flutter/src/widgets/framework.dart
Shared Preference takes time to save the details and I was fetching the data before saving it. So that's why I was getting null.
I solved it by delaying to navigate to Dashboard screen by this:
await FirebaseAuth.instance
.signInWithCredential(_phoneAuthCredential)
.then((AuthResult authRes) {
sharedPref.save("details", signInItem);
Timer(Duration(seconds: 2), () {
Navigator.pop(context);
Navigator.popAndPushNamed(context, DashboardScreen.id);
});
});
But thanks #TheSohan for letting me know where I was getting null.
In SharedPref class read method; use a null check before decoding the data.
Ex:
class SharedPref {
read(String key) async {
final prefs = await SharedPreferences.getInstance();
string data = prefs.getString(key)
if(data){
return json.decode(prefs.getString(key));
}
return data
}
similarly, add null check in loadSharedPrefs method.
loadSharedPrefs() async {
var decodedData = await sharedPref.read("details");
if(decodedData){
signInItem = SignInItem.fromJson(decodedData);
}
setState(() {});
}