How to keep an application from locking the screen in flutter?
Is there a flag to turn it off an on? Does flutter SDK expose this?
Something like keepAwake(true);
As support for the screen plugin that #Tree mentioned has been discontinued and there are some issues with it now, you can use wakelock.
Full disclosure: I am the author of this plugin, however, it is basically a port of the wakelock functionality from the screen plugin, with the issues fixed:
import 'package:wakelock/wakelock.dart';
// To keep the screen on:
Wakelock.enable(); // or Wakelock.toggle(on: true);
// To let the screen turn off again:
Wakelock.disable(); // or Wakelock.toggle(on: false);
Learn more.
I found plugin that does the job.
https://pub.dartlang.org/packages/screen
import 'package:screen/screen.dart';
// Prevent screen from going into sleep mode:
Screen.keepOn(true);
You also need to set permission for android
<uses-permission android:name="android.permission.WAKE_LOCK" />
This package does the work
https://pub.dev/packages/wakelock
It depends on Flutter Wakelock class.
Permissions
The wakelock plugin does not require any permissions on any platform.
This is because it only enables the screen wakelock and not any partial (CPU) wakelocks that would keep the app alive in the background.
How to Use it?
// to enable the Android and iOS wakelock
Wakelock.enable();
// to disables the wakelock again.
Wakelock.disable();
import 'package:flutter/material.dart';
import 'package:wakelock/wakelock.dart';
void main() {
runApp( MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
Wakelock.enable(); // Here :)
return MaterialApp(
home: MyHomePage(),
);
}
}
Note: You have to Stop and Run again
As #creativecreatorormaybenot already answered, you can use wakeLock to keep the screen on. But I wanted to add where to put the Wakelock.enable();.
Here a code snippet how I used it and it works fine for me:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
Wakelock.enable();
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MainScreen()
);
}
}
I hope it will fix your problem. Here is the link to the package: https://pub.dev/packages/wakelock
Related
I am using go_router flutter package for Flutter Web.
I am getting this error while reloading the website. The back button is working great but the reload causes this.
Assertion failed: org-dartlang-sdk:///flutter_web_sdk/lib/_engine/engine/window.dart:25:10
!_isUrlStrategySet
"Cannot set URL strategy more than once."
Below is the code for my main.dart:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:navigator_2/some_app.dart';
import 'details_page.dart';
void main() {
runApp( MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final GoRouter _router = GoRouter(
urlPathStrategy: UrlPathStrategy.path,
routes: [
GoRoute(path: '/',builder: (context,state)=> const SomeAppPage()),
GoRoute(path: '/details',builder: (context,state){
final query = state.queryParams['index'];
return DetailsPage(index: int.parse(query!));
}),
]);
return MaterialApp.router(
routeInformationParser: _router.routeInformationParser,
routerDelegate: _router.routerDelegate ,
title: 'Go Router Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
);
}
}
Divyam Makar's answer didn't work for me because I need to use ChangeNotifier subclass on my GoRouter definition, so when I moved the GoRouter initialisation to initState, I got the exception:
dependOnInheritedWidgetOfExactType<_InheritedProviderScope<MyCustomState?>>()
or dependOnInheritedElement() was called before
_MainWidgetState.initState() completed.
So, following the documentation, I set the Url Path Strategy in an upper level of the hierarchy, in the main method:
void main() {
GoRouter.setUrlPathStrategy(UrlPathStrategy.path);
runApp(App());
}
The url path strategy to remove the # character from url's should be set in main().
As of go_router 5.1.0, urlPathStrategy has been completely removed, so GoRouter.setUrlPathStrategy(UrlPathStrategy.path); would cause a build error.
In the 5.0 migration guide, instead of GoRouter.setUrlPathStrategy(UrlPathStrategy.path); replace with:
import 'package:flutter_web_plugins/url_strategy.dart';
void main() {
usePathUrlStrategy();
runApp(ExampleApp());
}
I got the answer. It was just that because GoRouter was defined in build function then during reload its called again and thus causing this error. Removing it and putting it in initState solves it.
I tried using the is_first_run package to check if it's the first time my app has been launched. It actually worked as intended the first time I ever tested it. It took the user to the Welcome page on first launch, and then subsequent launches went to the Sign up or Log in page. But any efforts to recreate it again to make sure it's working have failed, and instead it takes me straight to Sign up or Log in, even after uninstalling the app from my device, running flutter clean, deleting all cache and storage for the app, and testing it on a completely different device. Any reason why it's not working anymore?
Here is the entire code for my main file:
import 'package:screens/welcomepages/signup_or_login.dart';
import 'package:screens/welcomepages/welcome.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:config/theme.dart';
import 'package:is_first_run/is_first_run.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarBrightness: Brightness.dark));
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
var ifr = _checkFirstRun();
if (ifr == true) {
return MaterialApp(
theme: theme(),
debugShowCheckedModeBanner: false,
home: const Welcome(),
);
}
return MaterialApp(
theme: theme(),
debugShowCheckedModeBanner: false,
home: const SignUpOrLogIn(),
);
}
}
Future<bool> _checkFirstRun() async {
return await IsFirstRun.isFirstRun();
}
Any alternative solutions also welcome.
I think you should use Shared preferences for better state management.
However, with this library, you can try the reset() function.
After calling reset(), calling isFirstRun() will return true as long as the app is running. After a restart, it will return false again. The first call of isFirstCall() will return true, subsequent calls will return false again.
I need red status bar with white foreground for my entire app.
I'm using flutter_statusbarcolor package for this.
I did the following so far:
Added the package in pubsec.yaml
Imported the package in my main.dart file
Added the following lines of codes inside the build() of MyApp class
FlutterStatusbarcolor.setStatusBarColor(Colors.red[900]);
FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
Result:
The status bar's color is red(working as it should).
The foreground color is white. But on restart changes to black. On hot reload, changes back to white. But on restart, it'll change back to black.
Here is my complete code:
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
FlutterStatusbarcolor.setStatusBarColor(Colors.red[900]);
FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'App Title',
home: HomeScreen(),
);
}
}
I've also tried the following:
SystemChrome.setSystemUIOverlayStyle()
appBarTheme: Theme.of(context).appBarTheme.copyWith(brightness: Brightness.light)
Nothing's working. Can anyone please help me sustain the white foreground throughout the app?
You can try this from this Doc ==> setSystemUIOverlayStyle method
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.red,
);
return Placeholder(); // using As your Need
}
add this:
import 'package:flutter/services.dart'
use the code below after theme data
home: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
Hope it work...
When removing system overlays with SystemChrome.setEnabledSystemUIOverlays([]) the app does not expand to fill the screen.
Complete main.dart file:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setEnabledSystemUIOverlays([]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Container(
color: Colors.red,
),
);
}
}
Without SystemChrome.setEnabledSystemUIOverlays([]):
Flutter version: 1.22.2
I'm unable to reproduce with Flutter 1.22(stable) but in https://github.com/flutter/flutter/issues/14432 people seem to have had good results with
setting Scaffold.resizeToAvoidBottomPadding to true.
You can also try to update Flutter and/or changing channels. Perhaps even trying on a physical device.
I am looking to have an app with sidebar navigation and also authenticate user on starting the app. The sidebar function ensures the side navigation on every page of the application using the navigation states and the new rootpage ensures that the users get authenticated in order to use the applications. The two require to use a home: function and one cannot have the two in the main.dart file. Any ideas i can incorporate both of them
import 'package:flutter/material.dart';
import 'services/authentication.dart'; //authentication module
import 'sidebar/sidebar_layout.dart'; sidebar navigation
import 'pages/root_page.dart'; //page that looks if user has an id
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'M-Afya',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
primaryColor: Colors.white,
),
home: new RootPage(auth: new Auth()) //ensures one must be authenticated to use the application
home: SideBarLayout() //sidebar navigation
);
}
}
How can I do this?
Here is a video that will help you for switches between lgoin and home page + state initialization and you can add your sidebar accordingly. https://www.youtube.com/watch?v=Pl1rKBnmDkU