Reputation: 1087
I would like to develop a flutter app for mac desktop and access the macs powermetrics with sudo powermetrics
is there a way to ask the user for sudo privileges for this command on first run?
Upvotes: 5
Views: 5104
Reputation: 1244
Hi I am just playing with flutter and I was solving same question.
In general we need GUI version of sudo called from bash.
example of bash commnad to run dscacheutil which needs sudo:
/usr/bin/osascript -e 'do shell script "dscacheutil -flushcache 2>&1 etc" with administrator privileges'
Then I was trying to run this command via Process.run() in flutter but no success. Then I created testing bash script and I tried to run bash script directly using Process.run(). It told me then I don't have privileges.
So I had to change my App Sandbox value to NO in Xcode.
We have to open Runner.xcodeproj
directly inside macos
folder.
Then change App Sandbox to NO:
No we have to prepare our bash script:
#!/bin/bash
/usr/bin/osascript -e 'do shell script "dscacheutil -flushcache 2>&1 etc" with administrator privileges'
Save it somewhere and last step we can call this bash script in flutter.
void main() {
Process.run('/Users/nikix/Desktop/bash_test.sh',[]).then((result){
stdout.write(result.stdout);
stderr.write(result.stderr);
});
}
Now I am getting GUI prompt with sudo, it seems to work. But I really don't know if this is correct way. I am pretty new in flutter.
UPDATE:
I have tried to build flutter app flutter build macos
but bash script can't be run. Then I found this package called process_run
Then I was able to run custom bash script from builded app
In your yaml pubspec.yaml add that package:
dependencies:
flutter:
sdk: flutter
process_run: any
Next step is to allow Sanbox App for release version of app in xcode:
Last step run our bash code in Dart:
import 'package:process_run/shell.dart';
void main() {
var shell = Shell();
shell.run("""
#!/bin/bash
/usr/bin/osascript -e 'do shell script "dscacheutil -flushcache 2>&1 etc" with administrator privileges'
""").then((result){
print('Shell script done!');
}).catchError((onError) {
print('Shell.run error!');
print(onError);
});
};
Upvotes: 5