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) {
}
},
Related
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
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;
}
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();
});
}
Any idea what is wrong here?
I have a function which receive data from server by a rest call, which return Future object.
Future _function(){
var future = _getWithID('path');
future.then((data) {
List<SOMEOBJECT> SOMEOBJECT = data["entities"].map((v) {
return new SOMEOBJECT(
id: v["properties"]["id"],
name: titleize(v["properties"]["name"])
);
}).toList();
return new Future.value(SOMEOBJECT.process(SOMEOBJECT));
});
}
Model class for SOMEOBJECT
class SOMEOBJECT extends Model {
int id;
String name;
SOMEOBJECT({this.id, this.name});
static Map process(List<String> SOMEOBJECTS) {
// map = {name: A, value:[{name:list<String>},{name:list<String>}]}
return map;
}
}
Cache object which try to cache in browser
class CacheManager {
Map callbacks;
Map cache;
CacheManager(this.cache){
callbacks = {};
}
Future setData(String key, Function updateFunction) {
return chrome.storage.local.get(key).then( (resp){
cache[key] = resp[key];
return updateFunction().then((data) {
chrome.storage.local.set({key: data});
cache[key] = data;
}).whenComplete( () {
handleCallbacks(key);
});
});
}
void registerCallback(String key, Function callback) {
callbacks[key] = callback;
}
void handleCallbacks(String key){
if (callbacks[key] != null){
callbacks[key](cache[key]);
}
}
}
So I have these two lines before
cacheManager.registerCallback("SOMEOBJECT", loadSomeOBJECT);
cacheManager.setData('SOMEOBJECT', api._function);
and I am getting this error:
ERROR
NoSuchMethodError: method not found: 'then'
Receiver: null
Arguments: [Closure: (dynamic) => dynamic]
#0 Object._noSuchMethod (dart:core-patch/object_patch.dart:42)
#1 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#2 CacheManager.setData.<anonymous closure> (chrome-extension://ekfcndmmkincdeoolhcebmhcgmkmadip/helpers.dart:27:31)
#3 _RootZone.runUnary (dart:async/zone.dart:1149)
#4 _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:551)
#5 _Future._propagateToListeners (dart:async/future_impl.dart:637)
#6 _Future._completeWithValue (dart:async/future_impl.dart:424)
#7 _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:479)
#8 _microtaskLoop (dart:async/schedule_microtask.dart:41)
#9 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
#10 _ScheduleImmediateHelper._handleMutation (dart:html:49254)
#11 MutationObserver._create.<anonymous closure> (dart:html:27525)
this refer to the line which setData and callback from cache object. then the cache object will call the api.function to get the data from server, and then the raw data is served, it goes to process method in SOMEOBJECT class and return the MAP of JSON representation. Once the data back to cache manager to call the then on the future object it fails. with the error on the question. Any idea?
Thanks
I just had a brief look and saw
Future _function(){
var future = _getWithID('path');
return future.then((data) {
is missing a return. There might be other issues though.
Dart test code:
_doSomething2(callback(int x, int y)) {
callback(1, 2);
}
test('async test, check a function with 2 parameters', () {
new Timer(new Duration(milliseconds:100), _doSomething2(expectAsync2((x, y) {
expect(x, equals(1));
expect(y, equals(2));
})));
});
When I run it in Intellij-IDEA as "unittest", it passed, but there is some error message shown:
Testing started at PM11:08 ...
Unhandled exception:
The null object does not have a method 'call'.
NoSuchMethodError : method not found: 'call'
Receiver: null
Arguments: []
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1 _createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:11)
#2 _handleTimeout (timer_impl.dart:283)
#3 _handleTimeout (timer_impl.dart:292)
#4 _handleTimeout (timer_impl.dart:292)
#5 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:115)
Process finished with exit code 255
Where is wrong?
The test ends before the code inside the new Timer() is executed.
void main(List<String> args) {
test('async test, check a function with 2 parameters', () {
var callback = expectAsync0(() {});
new Timer(new Duration(milliseconds:100), () {
_doSomething2((x, y) {
expect(x, equals(1));
expect(y, equals(2));
callback();
});
});
});
}
This way the test doesn't end until callback is called.