skip to Main Content

I want to show some popups in a fluttter project to get location and disable battery optimazation whenever I open the app.

Is it possible to show popup from the first second without using any elevated button or something else? If it is possible, then please guide me how to do this.

I tried and showed this popup using ElevatedButton. But as I want to show this popup at the opening of the app, so this work using elevated button is not appropriate for me.

I used this code for showing popup using ElevatedButton:

import 'package:app_settings/app_settings.dart';
import 'package:flutter/material.dart';
import 'package:location/location.dart';

Future<void> main() async {
    runApp(MyApp());
}

class MyApp extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            home: Home(),
        );
    }
}

class Home extends StatefulWidget{
    @override
    _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
    Widget build(BuildContext context) {

      return  Scaffold(
          appBar: AppBar(
              title: Text("Turn On GPS in Flutter"),
              backgroundColor: Colors.redAccent,
          ),
          body: Container(
              alignment: Alignment.center,
              child: Column(
                  children:[

                      ElevatedButton(
                          onPressed: () async {
                              Location location = new Location();
                              bool ison = await location.serviceEnabled();
                              if (!ison) { //if defvice is off
                                    bool isturnedon = await location.requestService();
                                    if (isturnedon) {
                                        print("GPS device is turned ON");
                                    }else{
                                        print("GPS Device is still OFF");
                                    }
                              }
                          },
                          child: Text("Turn On GPS | Location Package")
                      ),

                      ElevatedButton(
                          onPressed: () async {
                          AppSettings.openLocationSettings();
                          },
                          child: Text("Turn On GPS | App Setting Package")
                      )
                  ]
              )
          ),
      );
    }
}


2

Answers


  1. **Please replace this code.**
    
    
    import 'package:flutter/material.dart';
    import 'package:app_settings/app_settings.dart';
    import 'package:location/location.dart';
    
    void main() {
     runApp(MyApp());
    }
    
      class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
      return MaterialApp(
       home: Home(),
      );
     }
    }
    
     class Home extends StatefulWidget {
      @override
      _HomeState createState() => _HomeState();
     }
    
     class _HomeState extends State<Home> {
    Location location = Location();
    
    @override
    void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _showLocationAndBatteryDialog();
      });
    }
    
      Future<void> _showLocationAndBatteryDialog() async {
       bool isLocationServiceEnabled = await 
       location.serviceEnabled();
       if (!isLocationServiceEnabled) {
       bool shouldRequestLocation = await showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('Enable Location Service'),
          content: Text('Please enable location service to use this 
           app.'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context, true);
              },
              child: Text('Enable'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context, false);
              },
              child: Text('Cancel'),
            ),
          ],
        ),
      );
      if (shouldRequestLocation) {
        await location.requestService();
      }
     }
    }
    
     @override
      Widget build(BuildContext context) {
      return Scaffold(
      appBar: AppBar(
        title: Text("Turn On GPS in Flutter"),
        backgroundColor: Colors.redAccent,
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () async {
                await _showLocationAndBatteryDialog();
              },
              child: Text("Show Location Dialog"),
                ),
              ],
            ),
          ),
        );
      }
    } 
    
    Login or Signup to reply.
  2. Location Permission: if location services are
    enabled and requests the user to enable them if they are not.

    Battery Optimization: To prompt the user to disable battery
    optimization, you would typically need to direct them to the battery
    optimization settings page on their device, as there is no direct API
    to disable battery optimization programmatically due to security
    reasons.

    For battery optimization, you can use the app_settings package or a
    similar package to open the battery optimization settings. Here’s how
    you can do this:

       import 'package:flutter/material.dart';
       import 'package:location/location.dart';
       import 'package:app_settings/app_settings.dart';
    
          class Home extends StatefulWidget {
      @override
      _HomeState createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
      Location location = new Location();
    
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addPostFrameCallback((_) {
          _showLocationAndBatteryDialog();
        });
      }
    
      Future<void> _showLocationAndBatteryDialog() async {
        bool isLocationServiceEnabled = await location.serviceEnabled();
        if (!isLocationServiceEnabled) {
          // Show dialog to enable location service
          bool shouldRequestLocation = await showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text('Enable Location Service'),
              content: Text('Please enable location service to use this app.'),
              actions: <Widget>[
                TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: Text('Enable'),
                ),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: Text('Cancel'),
                ),
              ],
            ),
          ) ?? false;
    
          if (shouldRequestLocation) {
            await location.requestService();
          }
        }
    
        // Check for battery optimization
        // Note: Direct disabling of battery optimization is not possible due to security restrictions
        // Instead, guide the user to the battery optimization settings
        bool isIgnoringBatteryOptimizations = await location.isIgnoringBatteryOptimizations();
        if (!isIgnoringBatteryOptimizations) {
          // Show dialog to navigate to battery optimization settings
          await showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text('Disable Battery Optimization'),
              content: Text('Please disable battery optimization for this app in settings to ensure it functions correctly.'),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    AppSettings.openBatteryOptimizationSettings();
                    Navigator.of(context).pop();
                  },
                  child: Text('Open Settings'),
                ),
              ],
            ),
          );
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Turn On GPS in Flutter"),
            backgroundColor: Colors.redAccent,
          ),
          body: Center(
            child: ElevatedButton(
              onPressed: _showLocationAndBatteryDialog,
              child: Text("Check Permissions"),
            ),
          ),
        );
      }
    }
    

    After checking and requesting the location service, it proceeds to
    check if the app is ignoring battery optimizations. If the app is not
    ignoring battery optimizations, it shows a dialog that directs the
    user to the battery optimization settings using
    AppSettings.openBatteryOptimizationSettings(). Remember, direct
    disabling of battery optimization by the app is not allowed for
    security and privacy reasons. You can only direct the user to the
    settings where they can manually disable it for your app.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search