So I made a testing Flutter app because I'm having problems with my bigger one and I wanted to try isolate the problem.
Whenever I try to call user.sendEmailVerification() it never actually sends the email. I added .then afterwards and checked if it did send and it says it did but I've tried everything so I'm hoping someone here can help me out!!
main.dart
import 'package:emailverifytest/verify.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(home: verify());
}
}
verify.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
class verify extends StatelessWidget {
const verify({Key? key}) : super(key: key);
void runTest() async {
try {
// await FirebaseAuth.instance.createUserWithEmailAndPassword(
// email: 'example#gmail.com', password: 'password');
await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: 'example#gmail.com', password: 'password')
.then((value) async {
await FirebaseAuth.instance.currentUser!.sendEmailVerification();
print('sent');
});
// User? user = await FirebaseAuth.instance.currentUser;
// if (user != null && !user.emailVerified) {
// await user.sendEmailVerification();
// print("here");
// }
} on FirebaseAuthException catch (e) {
print(e.code);
}
}
#override
Widget build(BuildContext context) {
runTest();
return const Scaffold();
}
}
Flutter doctor
[✓] Flutter (Channel stable, 3.0.1, on macOS 12.4 21F79 darwin-arm, locale en-NZ)
• Flutter version 3.0.1 at /Users/kaneviggers/Documents/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision fb57da5f94 (13 days ago), 2022-05-19 15:50:29 -0700
• Engine revision caaafc5604
• Dart version 2.17.1
• DevTools version 2.12.2
[✗] Android toolchain - develop for Android devices
✗ Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
`flutter config --android-sdk` to update to that location.
[✓] Xcode - develop for iOS and macOS (Xcode 13.4)
• Xcode at /Applications/Xcode.app/Contents/Developer
• CocoaPods version 1.11.3
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[!] Android Studio (not installed)
• Android Studio not found; download from https://developer.android.com/studio/index.html
(or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).
[✓] VS Code (version 1.67.2)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.42.0
I'll be online for the rest of the day, so I'll be quick to reply!
Cheers
-Kane
Related
Description:
In the Android platform, we have created an application with custom platform specific code to get the images of PDF document pages. So, we have converted the PDF file as Uint8List in the client side and passed those bytes to host side through the method channel. On doing this so, it throws out of memory exception. This happened when a PDF document with the size of 500 MB is converted and passed as bytes through the method channel.
Code snippet:
main.dart
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class PlatformChannel extends StatefulWidget {
const PlatformChannel({super.key});
#override
State<PlatformChannel> createState() => _PlatformChannelState();
}
class _PlatformChannelState extends State<PlatformChannel> {
final MethodChannel _channel = MethodChannel('samples.flutter.io/pdf');
int _pageCount = 0;
ByteData? bytes;
Uint8List? _documentBytes;
Future<Uint8List> _readDocumentData() async {
bytes = await DefaultAssetBundle.of(context)
.load('assets/sample.pdf');
return _documentBytes = bytes!.buffer.asUint8List();
}
Future<String?> initializePdfRenderer(Uint8List getBytes) async {
return _channel.invokeMethod('initializePdfRenderer', <String, dynamic>{
'documentBytes': getBytes,
});
}
Future<void> result() async {
Uint8List loadBytes = await _readDocumentData();
final String? pageCount = await initializePdfRenderer(loadBytes);
_pageCount = int.parse(pageCount!);
print(_pageCount);
}
#override
Widget build(BuildContext context) {
return Material(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: () async {
await result();
},
child: const Text('Get'),
),
),
],
),
],
),
);
}
}
void main() {
runApp(const MaterialApp(home: PlatformChannel()));
}
MainActivity.java
public class MainActivity extends FlutterActivity {
private static final String METHOD_CHANNEL = "samples.flutter.io/pdf";
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
new MethodChannel(flutterEngine.getDartExecutor(), METHOD_CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, Result result) {
if(call.method.equals("initializePdfRenderer")){
result.success(initializePdfRenderer((byte[]) call.argument("documentBytes")));
}
else {
result.notImplemented();
}
}
}
);
}
String initializePdfRenderer(byte[] path) {
try {
File file = File.createTempFile(
".viewer", ".pdf"
);
OutputStream stream = new FileOutputStream(file);
stream.write(path);
stream.close();
return String.valueOf(1);
} catch (Exception e) {
return e.toString();
}
}
}
Stack trace detail:
E/AndroidRuntime(25582): java.lang.OutOfMemoryError: Failed to allocate a 542281144 byte allocation with 12582912 free bytes and 253MB until OOM, target footprint 15013128, growth limit 268435456
E/AndroidRuntime(25582): at io.flutter.plugin.common.StandardMessageCodec.readBytes(StandardMessageCodec.java:320)
E/AndroidRuntime(25582): at io.flutter.plugin.common.StandardMessageCodec.readValueOfType(StandardMessageCodec.java:386)
E/AndroidRuntime(25582): at io.flutter.plugin.common.StandardMessageCodec.readValue(StandardMessageCodec.java:340)
E/AndroidRuntime(25582): at io.flutter.plugin.common.StandardMessageCodec.readValueOfType(StandardMessageCodec.java:434)
E/AndroidRuntime(25582): at io.flutter.plugin.common.StandardMessageCodec.readValue(StandardMessageCodec.java:340)
E/AndroidRuntime(25582): at io.flutter.plugin.common.StandardMethodCodec.decodeMethodCall(StandardMethodCodec.java:51)
E/AndroidRuntime(25582): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:260)
E/AndroidRuntime(25582): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/AndroidRuntime(25582): at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:319)
E/AndroidRuntime(25582): at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(Unknown Source:12)
E/AndroidRuntime(25582): at android.os.Handler.handleCallback(Handler.java:938)
E/AndroidRuntime(25582): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(25582): at android.os.Looper.loop(Looper.java:257)
E/AndroidRuntime(25582): at android.app.ActivityThread.main(ActivityThread.java:8246)
E/AndroidRuntime(25582): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(25582): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
E/AndroidRuntime(25582): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Flutter Doctor log:
[√] Flutter (Channel stable, 3.0.4, on Microsoft Windows [Version 10.0.19042.1706], locale en-US)
• Flutter version 3.0.4 at C:\Flutter new SDk 2.5\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 85684f9 (3 weeks ago), 2022-06-30 13:22:47 -0700
• Engine revision 6ba2af10bb
• Dart version 2.17.5
• DevTools version 2.12.2
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
• Android SDK at C:\Users\DeepikaRavi\AppData\Local\Android\sdk
• Platform android-31, build-tools 30.0.3
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Users\DeepikaRavi\AppData\Local\Google\Chrome\Application\chrome.exe
[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.2.5)
• Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community
• Visual Studio Community 2022 version 17.2.32616.157
• Windows 10 SDK version 10.0.20348.0
[√] Android Studio (version 2021.2)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
[√] VS Code (version 1.66.2)
• VS Code at C:\Users\DeepikaRavi\AppData\Local\Programs\Microsoft VS Code
• Flutter extension can be installed from:
https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[√] Connected device (3 available)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19042.1706]
• Chrome (web) • chrome • web-javascript • Google Chrome 103.0.5060.114
• Edge (web) • edge • web-javascript • Microsoft Edge 92.0.902.78
[√] HTTP Host Availability
• All required HTTP hosts are available
I'm trying to create an app where I can switch videos with swipes (similar to TikTok). My current implementation looks like this:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
List<String> urls = [
"https://movietrailers.apple.com/movies/oscilloscope/relaxer/relaxer-trailer-1_720p.mov",
"https://movietrailers.apple.com/movies/sony_pictures/the-front-runner/front-runner-trailer-1_720p.mov",
"https://movietrailers.apple.com/movies/independent/cant-stop-wont-stop-a-bad-boy-story/cant-stop-wont-stop-trailer-1_720p.mov",
"https://movietrailers.apple.com/movies/independent/at-first-light/at-first-light-trailer-1_720p.mov"
];
return MaterialApp(
home: PageView.builder(
itemBuilder: (ctx, index) => VideoScreen(url: urls[index]),
itemCount: urls.length,
scrollDirection: Axis.vertical,
),
);
}
}
class VideoScreen extends StatefulWidget {
final String url;
const VideoScreen({Key? key, required this.url}) : super(key: key);
#override
_VideoScreenState createState() => _VideoScreenState();
}
class _VideoScreenState extends State<VideoScreen> {
late VideoPlayerController controller;
void initController() async {
controller = VideoPlayerController.network(widget.url);
await controller.initialize();
controller.play();
}
#override
void initState() {
initController();
super.initState();
}
#override
Widget build(BuildContext context) {
if (controller.value.isInitialized) {
return const CircularProgressIndicator();
}
return SizedBox(
height: double.infinity,
child: AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: VideoPlayer(controller),
),
);
}
}
However, each initialization call o VideoPlayerController entails a complete freeze of the application for the duration of the video download. During this, I am not able to perform any actions in the application.
I'm using the newest version of package in my pubspec.yaml: video_player: ^2.2.16.
Here is the output of the flutter doctor command:
% flutter doctor -v
[✓] Flutter (Channel stable, 2.5.1, on macOS 12.1 21C52 darwin-arm, locale ru-RU)
• Flutter version 2.5.1 at /Users/rkfcccccc/documents/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision ffb2ecea52 (5 months ago), 2021-09-17 15:26:33 -0400
• Engine revision b3af521a05
• Dart version 2.14.2
[!] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
• Android SDK at /Users/rkfcccccc/Library/Android/sdk
✗ cmdline-tools component is missing
Run `path/to/sdkmanager --install "cmdline-tools;latest"`
See https://developer.android.com/studio/command-line for more details.
✗ Android license status unknown.
Run `flutter doctor --android-licenses` to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 13.2.1, Build version 13C100
• CocoaPods version 1.11.2
[✗] Chrome - develop for the web (Cannot find Chrome executable at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome)
! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[!] Android Studio (not installed)
• Android Studio not found; download from https://developer.android.com/studio/index.html
(or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).
[✓] VS Code (version 1.63.2)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.32.0
[✓] Connected device (1 available)
• rkfcccccc (mobile) iOS 15.2.1 19C63
Consider making use of state management such as Provider to handle the logic to initialize incoming indices and play current index. The same will be used to pause/remove the controller once the index is changed to a succeeding or preceding index.
just make sure you dispose your controller inside your VideoScreen
#override
void dispose() {
_controller.dispose();
super.dispose();
}
I'm trying to test my flutter app locally, connecting to my API locally. I have that application running on localhost:5000, and this is the code of a simple login form I've created.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'groups.dart';
import 'signup.dart';
class Token {
final String userToken;
Token({this.userToken});
factory Token.fromJson(Map<String, dynamic> json) {
print(json);
return Token(
userToken: json['title'],
);
}
}
class Login extends StatefulWidget {
Login({Key key}) : super(key: key);
#override
LoginState createState() => LoginState();
}
class LoginState extends State<Login> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
var userData = {};
void updateField(String value, String field) {
setState(() {
userData = {
...userData,
'$field': value,
};
});
}
Future<http.Response> sendLogin(user) {
final response = http.post(
Uri.parse('https://10.0.2.2:5000/api/User/Login'),
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(user),
);
print(response);
return response;
}
#override
Widget build(BuildContext context) {
return Material(
child: Column(children: <Widget>[
Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(), // these 2 form fields are commented out because they're already confirmed
TextFormField(), // to be working perfectly.
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
sendLogin(userData);
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Groups(),
));
}
},
child: Text('Submit'),
),
),
],
),
),
ElevatedButton(), // removed inside because it's a link to another page
);
}
}
I've looked at this link here how to solve flutter CERTIFICATE_VERIFY_FAILED error while performing a POST request?
That link led me to include more in my main.dart file, at least for testing purposes, ending that like this
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:mobile_v2/Packages/user-check.dart';
void main() {
HttpOverrides.global = new MyHttpOverrides();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Gathering',
home: UserCheck(),
);
}
}
class MyHttpOverrides extends HttpOverrides{
#override
HttpClient createHttpClient(SecurityContext context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
}
}
After making these changes, I ran a flutter pub get, just to be safe, and yet I'm still having the same issues. I've looked through most of the answers in that post, and it still gives the same result. Any other possible answers would be appreciated. Thank you. (flutter doctor below as well)
[√] Flutter (Channel stable, 2.0.5, on Microsoft Windows [Version 10.0.19041.985], locale en-US)
• Flutter version 2.0.5 at C:\src\flutter\flutter
• Framework revision adc687823a (5 weeks ago), 2021-04-16 09:40:20 -0700
• Engine revision b09f014e96
• Dart version 2.12.3
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
• Android SDK at C:\Users\ocdam\AppData\Local\Android\sdk
• Platform android-30, build-tools 30.0.3
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
[√] Android Studio (version 4.1.0)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
[√] IntelliJ IDEA Community Edition (version 2019.3)
• IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.3
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
[√] VS Code (version 1.56.2)
• VS Code at C:\Users\ocdam\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.22.0
[√] Connected device (3 available)
• sdk gphone x86 arm (mobile) • emulator-5554 • android-x86 • Android 11 (API 30) (emulator)
• Chrome (web) • chrome • web-javascript • Google Chrome 90.0.4430.212
• Edge (web) • edge • web-javascript • Microsoft Edge 90.0.818.49
• No issues found!
E/flutter ( 8743): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)]
Unhandled Exception: MissingPluginException(No implementation found
for method init on channel flutter.io/videoPlayer) E/flutter ( 8743):
MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7) E/flutter (
8743): E/flutter ( 8743): #1 MethodChannel.invokeMethod
(package:flutter/src/services/platform_channel.dart:329:12)
My flutter doctor -version
[✓] Flutter (Channel master, v1.16.4-pre.18, on Mac OS X 10.15.3
19D76, locale en-GB) • Flutter version 1.16.4-pre.18 at
/Users/olanrewaju/Dev/flutter • Framework revision c8efcb6 (6 days
ago), 2020-03-27 22:31:01 -0700 • Engine revision 3ee9e3d378 • Dart
version 2.8.0 (build 2.8.0-dev.17.0 1402e8e1a4)
[✓] Android toolchain - develop for Android devices (Android SDK
version 29.0.2) • Android SDK at /Users/olanrewaju/Library/Android/sdk
• Android NDK location not configured (optional; useful for native
profiling support) • Platform android-29, build-tools 29.0.2 • Java
binary at: /Applications/Android
Studio.app/Contents/jre/jdk/Contents/Home/bin/java • Java version
OpenJDK Runtime Environment (build
1.8.0_212-release-1586-b4-5784211) • All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1) • Xcode at
/Applications/Xcode.app/Contents/Developer • Xcode 11.3.1, Build
version 11C504 • CocoaPods version 1.8.4
[✓] Android Studio (version 3.6) • Android Studio at
/Applications/Android Studio.app/Contents • Flutter plugin version
44.0.2 • Dart plugin version 192.7761 • Java version OpenJDK Runtime Environment (build
1.8.0_212-release-1586-b4-5784211)
[✓] IntelliJ IDEA Ultimate Edition (version 2019.1) • IntelliJ at
/Applications/IntelliJ IDEA.app • Flutter plugin version 34.0.4 • Dart
plugin version 191.6183.88
[✓] VS Code (version 1.41.1) • VS Code at /Applications/Visual Studio
Code.app/Contents • Flutter extension version 3.8.1
[!] Connected device ! No devices available
You can reproduce the error by
main.dart
import 'package:video_player/video_player.dart';
import 'package:flutter/material.dart';
void main() => runApp(VideoApp());
class VideoApp extends StatefulWidget {
#override
_VideoAppState createState() => _VideoAppState();
}
class _VideoAppState extends State<VideoApp> {
VideoPlayerController _controller;
#override
void initState() {
super.initState();
_controller = VideoPlayerController.network(
'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_30MB.mp4')
..initialize().then((_) {
// Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Video Demo',
home: Scaffold(
body: Center(
child: _controller.value.initialized
? AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller),
)
: Container(),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_controller.value.isPlaying
? _controller.pause()
: _controller.play();
});
},
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
),
);
}
#override
void dispose() {
super.dispose();
_controller.dispose();
}
}
MainActivity.kt
import io.flutter.embedding.android.FlutterActivity
import android.content.pm.PackageManager
import android.os.Environment
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.io.File
class MainActivity: FlutterActivity() {
private val CHANNEL = "com.test/test"
private val PERMISSION = 8798798
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
.setMethodCallHandler { call: MethodCall?, result: MethodChannel.Result? ->
if (call?.method == "testAction") {
result?.success("Test")
} else {
result?.notImplemented()
}
}
}
}
add video_player: ^0.10.8+1 to dependencies.
Video player works if I don't have any method channel.
I am working with the Location 3.0.1 package in Flutter. I want to listen for location changes. My code (which is taken pretty much entirely from the github example for this package) is as follows:
class _HomePageState extends State<HomePage> {
StreamSubscription<LocationData> locationSubscription;
final Location location = new Location();
LocationData _locationData;
String _error;
var popupData;
PermissionStatus _permissionGranted;
_checkPermissions() async {
PermissionStatus permissionGrantedResult = await location.hasPermission();
setState(() {
_permissionGranted = permissionGrantedResult;
});
}
_requestPermission() async {
if (_permissionGranted != PermissionStatus.GRANTED) {
PermissionStatus permissionRequestedResult =
await location.requestPermission();
print(permissionRequestedResult);
setState(() {
_permissionGranted = permissionRequestedResult;
});
if (permissionRequestedResult != PermissionStatus.GRANTED) {
return;
} else{
_loadLocation();
}
}
else{
_loadLocation();
}
}
Future<void> _listenLocation() async {
locationSubscription =
location.onLocationChanged().handleError((dynamic err) {
setState(() {
_error = err.code;
});
locationSubscription.cancel();
}).listen((LocationData currentLocation) {
setState(() {
_error = null;
_locationData = currentLocation;
});
});
}
void _loadLocation() async {
_locationData = await location.getLocation();
_listenLocation();
}
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
if(_locationData == null){
_checkPermissions();
_requestPermission();
}
. . .
However, the stream subscription keeps getting triggered quite frequently (about once ever 2-3 seconds) (which causes setState to be called, and the whole screen to be rebuilt) even when the location is not changing (I am running this code on my emulator, so location should be static). Does anyone know why this is happening and how to fix it?
Output of flutter doctor:
[✓] Flutter (Channel stable, v1.12.13+hotfix.5, on Mac OS X 10.15.2 19C57, locale en-US)
• Flutter version 1.12.13+hotfix.5 at /Users/foo/development/flutter
• Framework revision 27321ebbad (4 months ago), 2019-12-10 18:15:01 -0800
• Engine revision 2994f7e1e6
• Dart version 2.7.0
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
• Android SDK at /Users/foo/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 28.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 11.3)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.3, Build version 11C29
• CocoaPods version 1.8.4
[✓] Android Studio (version 3.5)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 39.0.3
• Dart plugin version 191.8423
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
[✓] IntelliJ IDEA Ultimate Edition (version 2019.1.4)
• IntelliJ at /Applications/IntelliJ IDEA.app
• Flutter plugin version 38.1.3
• Dart plugin version 191.8593
[✓] Connected device (2 available)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 9 (API 28) (emulator)
• iPhone 11 Pro Max • B3536B50-C435-4442-9CF4-69D470B979CA • ios •
com.apple.CoreSimulator.SimRuntime.iOS-13-3 (simulator)
• No issues found!
If someone could just give me a snippet of code showing how to properly listen for updates, that would also be helpful (i.e. I'm not set on my code looking exactly like this).
You can copy paste run full code below
Because you put code in Widget build cause this issue
You can reference this https://medium.com/flutter-community/build-a-location-service-in-flutter-367a1b212f7a to build a Location Service
I made few change, you can directly see full code
You can use StreamProvider instead of await location.getLocation in Widget build
Youn can directly use location.requestPermission instead of Permission Handler
code snippt
return StreamProvider<UserLocation>(
create: (context) => LocationService().locationStream,
...
LocationService() {
// Request permission to use location
location.requestPermission().then((permissionStatus) {
if (permissionStatus == PermissionStatus.granted) {
// If granted listen to the onLocationChanged stream and emit over our controller
location.onLocationChanged.listen((locationData) {
working demo
full code
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:location/location.dart';
import 'dart:async';
class LocationService {
UserLocation _currentLocation;
var location = Location();
StreamController<UserLocation> _locationController =
StreamController<UserLocation>();
Stream<UserLocation> get locationStream => _locationController.stream;
LocationService() {
// Request permission to use location
location.requestPermission().then((permissionStatus) {
if (permissionStatus == PermissionStatus.granted) {
// If granted listen to the onLocationChanged stream and emit over our controller
location.onLocationChanged.listen((locationData) {
if (locationData != null) {
_locationController.add(UserLocation(
latitude: locationData.latitude,
longitude: locationData.longitude,
));
}
});
}
});
}
Future<UserLocation> getLocation() async {
try {
var userLocation = await location.getLocation();
_currentLocation = UserLocation(
latitude: userLocation.latitude,
longitude: userLocation.longitude,
);
} on Exception catch (e) {
print('Could not get location: ${e.toString()}');
}
return _currentLocation;
}
}
void main() {
runApp(MyApp());
}
class UserLocation {
final double latitude;
final double longitude;
UserLocation({this.latitude, this.longitude});
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return StreamProvider<UserLocation>(
create: (context) => LocationService().locationStream,
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: HomeView(),
)),
);
}
}
class HomeView extends StatelessWidget {
const HomeView({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
var userLocation = Provider.of<UserLocation>(context);
return Center(
child: Text(
'Location: Lat${userLocation?.latitude}, Long: ${userLocation?.longitude}'),
);
}
}