I did not deny permission but error is showing - geolocation

I have the following errors in my flutter app:
E/flutter ( 2893): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)]
Unhandled Exception: User denied permissions to access the device's
location. E/flutter ( 2893): #0
MethodChannelGeolocator.getCurrentPosition
(package:geolocator_platform_interface/src/implementations/method_channel_geolocator.dart:127:7)
E/flutter ( 2893): E/flutter ( 2893): #1
_RegisterScreenState.getCurrentLocation (package:megastore_sellers_app/authentication/register.dart:57:28)
E/flutter ( 2893): E/flutter ( 2893):
I/TextInputPlugin( 2893): Composing region changed by the framework.
Restarting the input method. D/InputConnectionAdaptor( 2893): The
input method toggled cursor monitoring on
My Code
getCurrentLocation() async
{
Position newPosition = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
position = newPosition;
placeMarks = await placemarkFromCoordinates(
position!.latitude,
position!.longitude,
);
Placemark pMark = placeMarks![0];
String completeAddress = '${pMark.subThoroughfare} ${pMark.thoroughfare}, ${pMark.subLocality} ${pMark.locality}, ${pMark.subAdministrativeArea}, ${pMark.administrativeArea} ${pMark.postalCode}, ${pMark.country}';
locationController.text = completeAddress;
}

Related

Dart Mqtt5 library throws InvalidHeaderException when publishing a message

I am trying to build a flutter UI app to publish and subscribe messages over mqtt5 protocol. I am using the library mqtt5_client: ^3.3.4
Subscription works like a charm. But while publishing the library throws InvalidHeaderException. The source code is not of much help in resolving the problem.
Thanks in advance for any pointer.
The full code and exception stack trace is given below. Problem is in the publish method in the call to publish
import 'dart:io';
import 'dart:convert';
import 'package:mqtt5_client/mqtt5_client.dart';
import 'package:mqtt5_client/mqtt5_server_client.dart';
class MQTTClient {
late MqttServerClient _client;
MQTTClient(String url, String clientId, int port) {
_client = MqttServerClient(url, clientId);
_client.port = port;
_client.keepAlivePeriod = 60;
_client.onConnected = onConnected;
_client.onDisconnected = onDisconnected;
MqttConnectMessage connectMessage =
MqttConnectMessage().withWillQos(MqttQos.atLeastOnce);
_client.connectionMessage = connectMessage;
_client.logging(on: true);
}
void subscribe(String topic) {
_client.onSubscribed = onSubscribed;
_client.subscribe(topic, MqttQos.atLeastOnce);
_client.updates.listen((List<MqttReceivedMessage<MqttMessage?>>? msg) {
final recMess = msg![0].payload as MqttPublishMessage;
List<int> msgbytes = (recMess.payload.message)!.cast<int>();
print(
'Received message: topic is ${msg[0].topic}, payload is ${utf8.decode(msgbytes)} ');
});
}
void publish(String topic, String message) {
final builder = MqttPayloadBuilder();
builder.addString(message);
_client.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!);
_client.published!.listen((event) {
print(
'Published topic: topic is ${event.variableHeader!.topicName}, with Qos ${event.header!.qos}');
});
}
Future<int> connect() async {
try {
await _client.connect();
} on MqttNoConnectionException catch (e) {
print('connect exception - $e');
} on SocketException catch (e) {
print('socket exception - $e');
}
if (_client.connectionStatus!.state == MqttConnectionState.connected) {
print('client connected');
} else {
print(
'client connection failed - disconnecting, status is ${_client.connectionStatus}');
_client.disconnect();
exit(-1);
}
return 0;
}
}
MqttSubscription onSubscribed(MqttSubscription subscription) {
print('subscribed $subscription');
return subscription;
}
void onConnected() {
print("client connected");
}
void onDisconnected() {
print('client disconnected');
}
The exception stacktrace is :
Unhandled exception:
mqtt-client::InvalidHeaderException: The supplied header is invalid. Header must be at least 2 bytes long.
#0 MqttHeader.readFrom (package:mqtt5_client/src/messages/mqtt_header.dart:69:7)
#1 new MqttHeader.fromByteBuffer (package:mqtt5_client/src/messages/mqtt_header.dart:19:5)
#2 MqttByteBuffer.isMessageAvailable (package:mqtt5_client/src/utility/mqtt_byte_buffer.dart:66:29)
#3 MqttServerConnection._onData (package:mqtt5_client/src/connectionhandling/server/mqtt_server_connection.dart:60:26)
#4 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10)
#5 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
#6 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
#7 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
#8 _StreamController._add (dart:async/stream_controller.dart:648:7)
#9 _StreamController.add (dart:async/stream_controller.dart:596:5)
#10 _Socket._onData (dart:io-patch/socket_patch.dart:2324:41)
#11 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10)
#12 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
#13 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
#14 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
#15 _StreamController._add (dart:async/stream_controller.dart:648:7)
#16 _StreamController.add (dart:async/stream_controller.dart:596:5)
#17 new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1849:33)
#18 _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1322:14)
#19 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
#20 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
#21 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:122:13)
#22 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:193:5)
The author of this library has resolved the issue; The error is specific to mqtt5 and is under investigation. The solution is to handle|ignore the exception as this occurs after the message is published. Another option is to use mqtt_client instead of mqtt5_client. Both methods work https://github.com/shamblett/mqtt_client/issues/438#issuecomment-1378346434

IOS status bar tap fails scroll to the top

I am using this package.
The package is a widget provided to the flutter scroll component drop-down refresh and pull up load.support android and ios
The package url is https://pub.dartlang.org/packages/pull_to_refresh
But this package has a bug !
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
class Example1 extends StatefulWidget {
#override
_Example1State createState() => new _Example1State();
}
class _Example1State extends State<Example1> {
// RefreshMode refreshing = RefreshMode.idle;
// LoadMode loading = LoadMode.idle;
RefreshController _refreshController;
List<Widget> data = [];
void _getDatas() {
for (int i = 0; i < 14; i++) {
data.add(new Card(
margin:
new EdgeInsets.only(left: 10.0, right: 10.0, top: 5.0, bottom: 5.0),
child: new Center(
child: new Text('Data $i'),
),
));
}
}
void enterRefresh() {
_refreshController.requestRefresh(true);
}
void _onOffsetCallback(bool isUp, double offset) {
// if you want change some widgets state ,you should rewrite the callback
}
#override
void initState() {
// TODO: implement initState
_getDatas();
_refreshController = new RefreshController();
super.initState();
}
Widget _headerCreate(BuildContext context, int mode) {
return new ClassicIndicator(
mode: mode,
refreshingText: "",
idleIcon: new Container(),
idleText: "Load more...",
);
}
// Widget _footerCreate(BuildContext context,int mode){
// return new ClassicIndicator(mode: mode);
// }
#override
Widget build(BuildContext context) {
return new Container(
child: new SmartRefresher(
enablePullDown: true,
enablePullUp: true,
controller: _refreshController,
onRefresh: (up) {
if (up)
new Future.delayed(const Duration(milliseconds: 2009))
.then((val) {
data.add(new Card(
margin: new EdgeInsets.only(
left: 10.0, right: 10.0, top: 5.0, bottom: 5.0),
child: new Center(
child: new Text('Data '),
),
));
_refreshController.scrollTo(_refreshController.scrollController.offset+100.0);
_refreshController.sendBack(true, RefreshStatus.idle);
setState(() {});
// refresher.sendStatus(RefreshStatus.completed);
});
else {
new Future.delayed(const Duration(milliseconds: 2009))
.then((val) {
data.add(new Card(
margin: new EdgeInsets.only(
left: 10.0, right: 10.0, top: 5.0, bottom: 5.0),
child: new Center(
child: new Text('Data '),
),
));
setState(() {});
_refreshController.sendBack(false, RefreshStatus.idle);
});
}
},
onOffsetChange: _onOffsetCallback,
child: new ListView.builder(
reverse: true,
itemExtent: 100.0,
itemCount: data.length,
itemBuilder: (context, index) => new Item(),
)));
}
}
class Item extends StatefulWidget {
#override
_ItemState createState() => new _ItemState();
}
class _ItemState extends State<Item> {
#override
Widget build(BuildContext context) {
return new Card(
margin:
new EdgeInsets.only(left: 10.0, right: 10.0, top: 5.0, bottom: 5.0),
child: new Center(
child: new Text('Data'),
),
);
}
#override
void dispose() {
// TODO: implement dispose
print("销毁");
super.dispose();
}
}
When I tap the status bar,can't scroll to the top!
I tried to debug this package, I found that in line 344 of the smart_refresher.dart file, just comment the controller property and scroll back to the top, like this
But the pull-down refresh action will give an error.
flutter: ══╡ EXCEPTION CAUGHT BY ANIMATION LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown while notifying listeners for AnimationController:
flutter: ScrollController not attached to any scroll views.
flutter: 'package:flutter/src/widgets/scroll_controller.dart': Failed assertion: line 110 pos 12:
flutter: '_positions.isNotEmpty'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter: https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #2 ScrollController.position (package:flutter/src/widgets/scroll_controller.dart:110:12)
flutter: #3 ScrollController.offset (package:flutter/src/widgets/scroll_controller.dart:118:24)
flutter: #4 _SmartRefresherState._buildWrapperByConfig.<anonymous closure> (package:pull_to_refresh/src/smart_refresher.dart:291:42)
flutter: #5 RefreshWrapperState._handleOffsetCallBack (package:pull_to_refresh/src/internals/indicator_wrap.dart:163:14)
flutter: #6 _AnimationController&Animation&AnimationEagerListenerMixin&AnimationLocalListenersMixin.notifyListeners (package:flutter/src/animation/listener_helpers.dart:124:19)
flutter: #7 AnimationController.value= (package:flutter/src/animation/animation_controller.dart:351:5)
flutter: #8 RefreshWrapperState._handleModeChange (package:pull_to_refresh/src/internals/indicator_wrap.dart:171:25)
flutter: #9 ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:208:21)
flutter: #10 ValueNotifier.value= (package:flutter/src/foundation/change_notifier.dart:264:5)
flutter: #11 Wrapper.mode= (package:pull_to_refresh/src/internals/indicator_wrap.dart:31:43)
flutter: #12 RefreshWrapperState.onDragEnd (package:pull_to_refresh/src/internals/indicator_wrap.dart:157:14)
flutter: #13 _SmartRefresherState._handleScrollEnd (package:pull_to_refresh/src/smart_refresher.dart:120:40)
flutter: #14 _SmartRefresherState._dispatchScrollEvent (package:pull_to_refresh/src/smart_refresher.dart:133:16)
flutter: #15 NotificationListener._dispatch (package:flutter/src/widgets/notification_listener.dart:125:27)
flutter: #16 Notification.visitAncestor (package:flutter/src/widgets/notification_listener.dart:45:20)
flutter: #17 _ScrollNotification&LayoutChangedNotification&ViewportNotificationMixin.visitAncestor (package:flutter/src/widgets/scroll_notification.dart:31:18)
flutter: #18 Element.visitAncestorElements (package:flutter/src/widgets/framework.dart:3344:39)
flutter: #19 Notification.dispatch (package:flutter/src/widgets/notification_listener.dart:59:12)
flutter: #20 ScrollActivity.dispatchScrollUpdateNotification (package:flutter/src/widgets/scroll_activity.dart:96:92)
flutter: #21 ScrollPosition.didUpdateScrollPositionBy (package:flutter/src/widgets/scroll_position.dart:654:14)
flutter: #22 ScrollPosition.setPixels (package:flutter/src/widgets/scroll_position.dart:219:9)
flutter: #23 ScrollPositionWithSingleContext.setPixels (package:flutter/src/widgets/scroll_position_with_single_context.dart:84:18)
flutter: #24 BallisticScrollActivity.applyMoveTo (package:flutter/src/widgets/scroll_activity.dart:547:21)
flutter: #25 BallisticScrollActivity._tick (package:flutter/src/widgets/scroll_activity.dart:534:10)
flutter: #26 _AnimationController&Animation&AnimationEagerListenerMixin&AnimationLocalListenersMixin.notifyListeners (package:flutter/src/animation/listener_helpers.dart:124:19)
flutter: #27 AnimationController._tick (package:flutter/src/animation/animation_controller.dart:697:5)
flutter: #28 Ticker._tick (package:flutter/src/scheduler/ticker.dart:228:5)
flutter: #29 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
flutter: #30 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleBeginFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:906:11)
flutter: #31 __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.forEach (dart:collection/runtime/libcompact_hash.dart:370:8)
flutter: #32 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleBeginFrame (package:flutter/src/scheduler/binding.dart:904:17)
flutter: #33 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleBeginFrame (package:flutter/src/scheduler/binding.dart:834:5)
flutter: #34 _invoke1 (dart:ui/hooks.dart:168:13)
flutter: #35 _beginFrame (dart:ui/hooks.dart:138:3)
flutter: (elided 2 frames from class _AssertionError)
flutter:
flutter: The AnimationController notifying listeners was:
flutter: AnimationController#96484(⏭ 1.000; paused)
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: Another exception was thrown: ScrollController not attached to any scroll views.
[VERBOSE-2:shell.cc(184)] Dart Error: Unhandled exception:
'package:flutter/src/widgets/scroll_controller.dart': Failed assertion: line 110 pos 12: '_positions.isNotEmpty': ScrollController not attached to any scroll views.
#0 _AssertionError._doThrowNew (dart:core/runtime/liberrors_patch.dart:40:39)
#1 _AssertionError._throwNew (dart:core/runtime/liberrors_patch.dart:36:5)
#2 ScrollController.position (package:flutter/src/widgets/scroll_controller.dart:110:12)
#3 ScrollController.offset (package:flutter/src/widgets/scroll_controller.dart:118:24)
#4 _Example1State.build.<anonymous closure>.<anonymous closure> (package:example/ui/Example1.dart:76:83)
#5 _RootZone.runUnary (dart:async/zone.dart:1379:54)
#6 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
#7 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45)
#8 Future._propagateToListeners (dart:async/future_impl.dart:671:32)
#9 Future._complete (dart:as<…>
Relevant doctor info:
[✓] Flutter (Channel dev, v0.11.6, on Mac OS X 10.13.6 17G65, locale
zh-Hans-CN) [✓] Android toolchain - develop for Android devices
(Android SDK 28.0.3) [✓] iOS toolchain - develop for iOS devices
(Xcode 10.1) [✓] Android Studio (version 3.2)
[✓] VS Code (version> 1.29.1)
[✓] Connected device (1 available)
Please help me solve this bug, thank you.

Flutter using videoplayer in a listview returning multiple errors

I have a tabBarView with a listview in one of the tabs.I have the gesture detector below inside the listview. I am trying to show some newtwork videos.
VideoPlayerController playercontroller;
VideoPlayerController retcontroller(String varainatVideo){
if(playercontroller == null){
playercontroller = VideoPlayerController.network(varainatVideo);
}
return playercontroller;
}
GestureDetector(
child:AspectRatio(
aspectRatio: 16/9,
child:Stack(
children:<Widgets>[
Chewie(
retcontroller(stringVideo),
cupertinoProgressColors: ChewieProgressColors(),
showControls:false,
),
]
)
)
);
whenever I switch from that tab bar to another and try to navigate to another page in the second tabBar I get a black screen instead of the normal page.but when I remove the videoPage I dont get this problem and get this in the console
I/flutter (19985): Another exception was thrown: There are multiple heroes that share the same tag within a subtree.
I/flutter (19985): Another exception was thrown: There are multiple heroes that share the same tag within a subtree.
logs from the Debug console:
I have tried to figure out what, but I cant seem to get the Hero Tag associated with the videoPlayerController in order to set it to null.
I/flutter (19985): ══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (19985): The following assertion was thrown during a scheduler callback:
I/flutter (19985): There are multiple heroes that share the same tag within a subtree.
I/flutter (19985): Within each subtree for which heroes are to be animated (typically a PageRoute subtree), each Hero
I/flutter (19985): must have a unique non-null tag.
I/flutter (19985): In this case, multiple heroes had the following tag:
I/flutter (19985): VideoPlayerController#3144c(VideoPlayerValue(duration: null, size: null, position: 0:00:00.000000,
I/flutter (19985): buffered: [], isPlaying: false, isLooping: false, isBuffering: falsevolume: 1.0, errorDescription:
I/flutter (19985): null))
I/flutter (19985): Here is the subtree for one of the offending heroes:
I/flutter (19985): # Hero(tag: VideoPlayerController#3144c(VideoPlayerValue(duration: null, size: null, position: 0:00:00.000000, buffered: [], isPlaying: false, isLooping: false, isBuffering: falsevolume: 1.0, errorDescription: null)), state: _HeroState#b5c8f)
I/flutter (19985): # └KeyedSubtree-[GlobalKey#44acd]
I/flutter (19985): # └AspectRatio(aspectRatio: 1.7, renderObject: RenderAspectRatio#78caa relayoutBoundary=up2)
I/flutter (19985): # └VideoPlayer(state: _VideoPlayerState#62908)
I/flutter (19985): # └Container
I/flutter (19985): # └LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#9e9b5)
I/flutter (19985): # └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#1b4cb)
I/flutter (19985):
I/flutter (19985): When the exception was thrown, this was the stack:
I/flutter (19985): #0 Hero._allHeroesFor.visitor.<anonymous closure> (package:flutter/src/widgets/heroes.dart:191:13)
I/flutter (19985): #1 Hero._allHeroesFor.visitor (package:flutter/src/widgets/heroes.dart:201:10)
I/flutter (19985): #2 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:4784:14)
you should not use singleton VideoPlayerController for multiple Chewie instance, Chewie use controller(the first arguments) as hero's tag
class Videos extends StatefulWidget {
#override
_VideoPlayerPageState createState() => _VideosState();
}
class _VideosState extends State<Videos> {
List<String> videoList;
#override
Widget build(BuildContext context) {
// TODO: implement build
final videoList = _dir
.listSync()
.map((item) => item.path)
.where((item) =>
item.endsWith(".mp4") ||
item.endsWith(".avi") ||
item.endsWith(".webm"))
.toList(growable: false);
if (videoList != null) {
if (videoList.length > 0) {
return ListView.builder(
padding: EdgeInsets.only(left: 10, right: 10, bottom: 16),
itemBuilder: (BuildContext _context, int index) {
if (index >= videoList.length) {
return null;
}
return VideoPlayerScreen(
path: videoList[index],
);
});
}
}
return VideoPlayerScreen(
path: videoList[0],
);
}
}

fetch data then build listview

am trying to fetch data and then display it in a listview .. first i will take a hash value and then compare it with the hash i have saved if its the same then i will take the saved json data if not i will call the api ... like this:
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
File f = File('$path/mypollshash.txt');
if (f.existsSync()) {
print('exists');
String contents = await f.readAsString();
content = contents;
fetchHash();
} else {
print('not exists');
fetch();
}
return f;
}
Future checkfileexist() async {
try {
final file = await _localFile;
String contents = await file.readAsString();
content = contents;
} catch (e) {
//return 'nothing';
}
}
Future<File> writehash(String hash) async {
final file = await _localFile;
return file.writeAsString('$hash', mode: FileMode.write);
}
Future<File> get _localjson async {
final path = await _localPath;
return File('$path/mypolls.json');
}
Future<File> writejson(String json) async {
final file = await _localjson;
return file.writeAsString('$json', mode: FileMode.write);
}
Future readjson() async {
try {
final file = await _localjson;
String contents = await file.readAsString();
content = contents;
setState(() {
polls = pollsFromJson(content);
});
writejson(pollsToJson(polls));
writehash(polls.hash);
print('here');
// return contents;
} catch (e) {
print('there');
print(e);
// If we encounter an error, return 0
//return 'nothing';
}
}
fetch() async {
String data =
await DefaultAssetBundle.of(context).loadString("assets/mypolls.json");
setState(() {
polls = pollsFromJson(data);
});
writejson(pollsToJson(polls));
writehash(polls.hash);
}
fetchHash() async {
String data = await DefaultAssetBundle.of(context)
.loadString("assets/pollshash.json");
print(content);
final pollshash = pollshashFromJson(data);
if (content == pollshash.hash) {
print('take from the saved json');
readjson();
} else {
print('call api');
fetch();
}
}
and am calling it here:
#override
void initState() {
super.initState();
checkfileexist();
}
the problem is once the page is launched i will get the red error flutter screen that the length is null .. because the data is not fetched yet .. and then the list will be displayed ..
How i can fetch the data fisrt and then build the list so i will not get the error?
also the functions keeps repeating over and over again since am getting theses messages:
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
I/flutter ( 3556): exists
I/flutter ( 3556):
I/flutter ( 3556): call api
I/flutter ( 3556): exists
I/flutter ( 3556): d1f4bd60f52991d100adafa416f48b52
I/flutter ( 3556): take from the saved json
I/flutter ( 3556): here
.....
how can i call it only once? when the page is first launched?
you need to use a FutureBuilder
https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html
see the sample code, where '_calculation' for you is the source of data.
It needs to be wrapped in a Future.
Try this
Widget _myBuild() {
return FutureBuilder(
future: _fetchData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
// Update UI with data
} else if (snapshot.hasError) {
// show error
}
// show progress indicator
CircularProgressIndicator();
});
}

How to set image as wallpaper in flutter?

I'm confusing in how to set an image as wallpaper in flutter, I have tried to use this code below reference from here!
my flutter code:
in this code, I tried to make file from URL
//get URL image and save it and create a file
_setWallp(String imageUrl) async {
try {
var httpClient = http.Client();
var list = await httpClient.readBytes(imageUrl);
final tempDir = await getTemporaryDirectory();
final file = await new Io.File('${tempDir.path}/image.jpg').create();
file.writeAsBytes(list);
final channel = const MethodChannel('setwallpaper');
channel.invokeMethod('shareFile', 'image.jpg');
} catch (e) {
print('Share Error :$e');
}
}
my java code :
in this java code, I tried to set bitmap as wallpaper from file path that I created in flutter
//call method channel from flutter
private static final String SHARE_CHANNEL = "setwallpaper";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(this.getFlutterView(), SHARE_CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
public final void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("shareFile")) {
shareFile((String) methodCall.arguments);
}
}
});
}
private void shareFile(String path) {
File imgFile = new File(this.getApplicationContext().getCacheDir(), path);
// set bitmap to wallpaper
Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
WallpaperManager wm = WallpaperManager.getInstance(this);
try{
wm.setBitmap(bitmap);
}catch (IOException e){
Log.e(TAG, "shareFile: cannot set image as wallpaper",e );
}
}
}
debug console message:
//message from console
E/flutter (10376): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (10376): PlatformException(error, Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference, null)
E/flutter (10376): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:547:7)
E/flutter (10376): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:279:18)
E/flutter (10376): <asynchronous suspension>
E/flutter (10376): #2 FullScreenState._setWallp (file:///D:/fltr/cat_wallpapers/lib/fullscreen.dart:111:15)
E/flutter (10376): <asynchronous suspension>
E/flutter (10376): #3 FullScreenState.build.<anonymous closure> (file:///D:/fltr/cat_wallpapers/lib/fullscreen.dart:71:31)
E/flutter (10376): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:494:14)
E/flutter (10376): #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:549:30)
E/flutter (10376): #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter (10376): #7 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:161:9)
E/flutter (10376): #8 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:94:7)
E/flutter (10376): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
E/flutter (10376): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
E/flutter (10376): #11 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
E/flutter (10376): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:143:19)
E/flutter (10376): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
E/flutter (10376): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
E/flutter (10376): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
E/flutter (10376): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
E/flutter (10376): #17 _invoke1 (dart:ui/hooks.dart:134:13)
E/flutter (10376): #18 _dispatchPointerDataPacket (dart:ui/hooks.dart:91:5)
D/EGL_emulation(10376): eglMakeCurrent: 0xb429e760: ver 2 0
I/FlutterActivityDelegate(10376): onResume setting current activity to this
D/EGL_emulation(10376): eglCreateContext: 0xb429e820: maj 2 min 0 rcv 2
D/EGL_emulation(10376): eglMakeCurrent: 0xb429e820: ver 2 0
D/EGL_emulation(10376): eglMakeCurrent: 0xb429e760: ver 2 0
D/EGL_emulation(10376): eglMakeCurrent: 0xb429e820: ver 2 0
I/flutter (10376): Another exception was thrown: type 'Future<dynamic>' is not a subtype of type 'Future<File>' //didn't understand about this
need help.. thank you
Using Dio library...Make Sure That First You Download The Image And Once Downloaded Set As Wallpaper
Future<Null> setWallpaper() async {
Dio dio = Dio();
try {
var dir = await getTemporaryDirectory();
await dio.download(widget.img, "${dir.path}/myimage.jpeg",
onProgress: (rec, total) {
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
print(progressString);
if (progressString == "100%") {
_setWallpaer();
}
});
});
} catch (e) {}
setState(() {
downloading = false;
progressString = "Completed";
});}
Future<Null> _setWallpaer() async {
String setWallpaper;
try {
final int result =
await platform.invokeMethod('setWallpaper', 'myimage.jpeg');
setWallpaper = 'Wallpaer Updated....';
} on PlatformException catch (e) {
setWallpaper = "Failed to Set Wallpaer: '${e.message}'.";
}
setState(() {
_setWallpaper = setWallpaper;
});}
You Can See Full Source Code If It Can Help.....
https://github.com/pratiktimer/flutterwallpaper
Here error is created due to the Methodchannel invokemethod. So, this is solved in
Wallpaper plugin. Which can be use for Setting Wallpaper.
onPressed: () async {
try {
// path_provider: any
// async_wallpaper: any
// import 'package:async_wallpaper/async_wallpaper.dart';
// import 'package:path_provider/path_provider.dart';
// import 'package:flutter/services.dart';
// import 'dart:io';
ByteData imagebyte = await rootBundle
.load('assets/images/kissing_image_real.png');
final temp = await getTemporaryDirectory();
final path = '${temp.path}/image1.jpg';
File(path).writeAsBytesSync(imagebyte.buffer.asUint8List());
AsyncWallpaper.setWallpaperFromFile(
path, AsyncWallpaper.HOME_SCREEN)
.whenComplete(() {
ProgressBar.stop();
Get.snackbar('Success', 'New Wallpaper set',
colorText: Colors.white);
});
} catch (e) {
}
},

Resources