5

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?

m1416
  • 1,049
  • 12
  • 22

1 Answers1

5

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.

enter image description here

Then change App Sandbox to NO:

enter image description here

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:

enter image description here

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);
    });
};
TomRavn
  • 1,134
  • 14
  • 30
  • 1
    Best information from all over the internet. This should be accepted as answer. – Saikat halder Jun 23 '23 at 07:28
  • @Saikathalder - Thank you! I am glad it is still valid. I don't work with flutter for some time now. Have a great day! – TomRavn Jun 23 '23 at 16:39
  • by any chance do you know how do I run a executable with this? For example: run as simple as 'rclone --version' ? I have copied executables and tried this, which work in debug mode. But when I build macos, it does not work anymore. – Saikat halder Jun 23 '23 at 19:55