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.
Related
[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()),
),
],
),
),
),
);
}
}
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;
});
}
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(() {});
}
I'm beginning with this language and trying to create an application that can receive messages from a server (via websocket) and display them in a ListView.
I created a class in a dedicated file to transform this messages into entities.
But it seems, from the trace, that the class type I use in several files doesn't seem to be... "the same".
The trace :
E/flutter ( 9655): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'Example' is not a subtype of type 'Example' of 'example' where
E/flutter ( 9655): Example is from package:exampleProject/components/Example.dart
E/flutter ( 9655): Example is from package:exampleProject/components/example.dart
E/flutter ( 9655):
E/flutter ( 9655): #0 Plugin._onMessageReceived.<anonymous closure> (package:exampleProject/plugin.dart:35:15)
E/flutter ( 9655): #1 Iterable.forEach (dart:core/iterable.dart:279:30)
E/flutter ( 9655): #2 Plugin._onMessageReceived (package:exampleProject/plugin.dart:31:16)
E/flutter ( 9655): #3 WebSocketsNotifications._onReceptionOfMessageFromServer.<anonymous closure> (package:exampleProject/websockets.dart:95:15)
E/flutter ( 9655): #4 Iterable.forEach (dart:core/iterable.dart:279:30)
E/flutter ( 9655): #5 WebSocketsNotifications._onReceptionOfMessageFromServer (package:exampleProject/websockets.dart:94:16)
E/flutter ( 9655): #6 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter ( 9655): #7 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter ( 9655): #8 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter ( 9655): #9 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
E/flutter ( 9655): #10 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
E/flutter ( 9655): #11 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:134:11)
E/flutter ( 9655): #12 _ForwardingStream._handleData (dart:async/stream_pipe.dart:100:10)
E/flutter ( 9655): #13 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:166:13)
E/flutter ( 9655): #14 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter ( 9655): #15 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter ( 9655): #16 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter ( 9655): #17 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
E/flutter ( 9655): #18 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
E/flutter ( 9655): #19 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:766:19)
E/flutter ( 9655): #20 _StreamController._add (dart:async/stream_controller.dart:642:7)
E/flutter ( 9655): #21 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter ( 9655): #22 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter ( 9655): #23 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter ( 9655): #24 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
E/flutter ( 9655): #25 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
E/flutter ( 9655): #26 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:766:19)
E/flutter ( 9655): #27 _StreamController._add (dart:async/stream_controller.dart:642:7)
E/flutter ( 9655): #28 _StreamController.add (dart:async/stream_controller.dart:588:5)
E/flutter ( 9655): #29 new _WebSocketImpl._fromSocket.<anonymous closure> (dart:_http/websocket_impl.dart:1143:21)
E/flutter ( 9655): #30 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter ( 9655): #31 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter ( 9655): #32 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter ( 9655): #33 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
E/flutter ( 9655): #34 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
E/flutter ( 9655): #35 _SinkTransformerStreamSubscription._add (dart:async/stream_transformers.dart:70:11)
E/flutter ( 9655): #36 _EventSinkWrapper.add (dart:async/stream_transformers.dart:17:11)
E/flutter ( 9655): #37 _WebSocketProtocolTransformer._messageFrameEnd (dart:_http/websocket_impl.dart:336:22)
E/flutter ( 9655): #38 _WebSocketProtocolTransformer.add (dart:_http/websocket_impl.dart:231:46)
E/flutter ( 9655): #39 _SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:122:24)
E/flutter ( 9655): #40 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter ( 9655): #41 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter ( 9655): #42 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter ( 9655): #43 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
E/flutter ( 9655): #44 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
E/flutter ( 9655): #45 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:766:19)
E/flutter ( 9655): #46 _StreamController._add (dart:async/stream_controller.dart:642:7)
E/flutter ( 9655): #47 _StreamController.add (dart:async/stream_controller.dart:588:5)
E/flutter ( 9655): #48 _Socket._onData (dart:io-patch/socket_patch.dart:1831:41)
E/flutter ( 9655): #49 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter ( 9655): #50 _CustomZone.runUn
Here's my entity class :
// example.dart
class Example {
String name;
Example.fromJson(Map<String, dynamic> decodedJson) {
name = decodedJson['name'];
}
}
Here's the plugin that communicates with the socket manager and receives messages from it AND transforms the content into an entity :
// plugin.dart
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:exampleProject/websockets.dart';
import 'package:exampleProject/components/Example.dart';
Plugin plugin = new Plugin();
class Plugin {
static final Plugin _plugin = new Plugin._internal();
factory Plugin() => _plugin;
Plugin._internal() {
// Initialize sockets
sockets.initCommunication();
sockets.addListener(_onMessageReceived);
}
_onMessageReceived(message) {
Map<String, dynamic> decodedJson = json.decode(message);
_listeners.forEach((Function callback) {
// --------------------------------------------------------------< Creating the class instance
Example example = Example.fromJson(decodedJson);
// --------------------------------------------------------------< Send it to listeners
callback(example);
});
}
ObserverList<Function> _listeners = new ObserverList<Function>();
addListener(Function callback) {
_listeners.add(callback);
}
removeListener(Function callback) {
_listeners.remove(callback);
}
}
My main :
// main.dart
import 'package:flutter/material.dart';
import 'package:exampleProject/websockets.dart';
import 'package:exampleProject/plugin.dart';
import 'package:exampleProject/components/Example.dart';
void main() => runApp(App());
class App extends StatefulWidget {
#override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
// --------------------------------------------------------------< List
List<Example> examples = [];
#override
void initState() {
super.initState();
plugin.addListener(_onMessageReceived);
}
#override
void dispose() {
plugin.removeListener(_onMessageReceived);
super.dispose();
}
// --------------------------------------------------------------< List insert
_onMessageReceived(Example example) {
examples.insert(0, example);
// Force render
setState(() {});
}
[...]
}
What did I miss ?
Thank you in advance for your help
This line:
import 'package:exampleProject/components/Example.dart';
should be:
import 'package:exampleProject/components/example.dart';
since that's what it's called. The class name is Example but the file name is not.
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)