Undefined name 'navigator' in flutter - flutter

I have a StatefulWidget for page in flutter. On the press of a button I call the following method:
IconButton(
icon: Icon(Icons.photo),
iconSize: 25.0,
color: Theme.of(context).primaryColor,
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CallPage(title:contact)),
);
},
),
CallPage is another statefulWidget from which I am trying to create local and remote RTCVideoRenderers.
I use the following code to get the userMedia: video and audio from the navigator.
_getUserMedia() async {
final Map<String, dynamic> mediaConstraints = {
'audio': false,
'video': {'facingMode': 'user'}
};
if(await Permission.camera.request().isGranted) {
if(await Permission.microphone.request().isGranted){
MediaStream _localStream = await navigator.getUserMedia(mediaConstraints);
_localRenderer.srcObject = _localStream;
return _localStream;
}
}
}
Here, the Dart Analysis is throwing an error:
error: Undefined name 'navigator'. (undefined_identifier at [chatapp] lib/home/call_page.dart:99)
I am going crazy now! This exact app was working a few minutes ago. Suddenly it stopped working.
I have tried deleting the build directory, running flutter clean, restarting the project, everything!!
Please HELP!

The class name navigator has changed to MediaDevices in the flutter-webrtc package just on the day before this question was asked! Hope it helps someone.

Related

How to wait seState to be finished and widgets to be built before calling another function?

Hi StackOverFlow community,
that's my first question here and I'm glad to be part of this community as it already helped me in plenty of things. I looked on this topic and didn't manage to find anything.
I would like to redirect the DefaultTabController to the new tab created after waiting that it's loaded and built.
I managed to find a workaround with the awaiting a Future.delayed wrapping setState but I don't think it's the best solution out there.
When not using this FutureDelayed I get an error due to the fact that the button function is trying to redirect to a tab not yet crated as the DefaultTabController has not been yet rebuilt.
Function for adding a new tab inside a bottomSheet
Future<int> _addNewTab() async {
await showModalBottomSheet(
...
...
IconButton(
onPressed: () {
final isValid =
_formKey.currentState!.validate();
if (!isValid) {
return;
}
Navigator.pop(context);
setState(() {
_tabs
.add(_newTab.text);
});
}
return _tabs.lenght-1;
Widget inside which I call the function
return DefaultTabController(
...
...
floatingActionButton: Padding(
//button to add a new tab
padding: const EdgeInsets.only(bottom: 25.0),
child: IconButton(
icon: Icon(
Icons.add_circle,
size: 55,
),
onPressed: () async {
var page = await _addNewTab();
//awaiting this future delayed because we can't show a page which is not built yet
await Future.delayed(const Duration(milliseconds: 10),
() {
setState(() {});
});
//moving to the new tab built after awaiting it
if (mounted) { //checking that context is still alive and usable
DefaultTabController.of(context)!.animateTo(page);
}
},
Thanks a lot for your help in advance :)
Thanks to Gwhyyy I discovered about SchedulerBinding.
Here a link with a similar question already answered with different solutions hoping it helps.
Flutter: Run method on Widget build complete
Have a good day!
yes, you have right, using the Future to wait for the 10 milliseconds fixes it but it's not the best solution.
instead :
first import the scheduler package, it's built-in in flutter, add this on top of your file :
import 'flutter/scheduler.dart';
then, replace this:
await Future.delayed(const Duration(milliseconds: 10),
() {
setState(() {});
});
with this:
SchedulerBinding.instance.addPostFrameCallback(
(_){
setState(() {});
})
this will schedule the SetState(() {}) just one frame after it finishes executing all the code in that onPressed function, so the result will be an immediate SetState(() {}) after your page is on.

I'm trying to use shared_preferences to implement "favorites" functionality in flutter

I'm trying to create a "favorites" function using shared_preferences in flutter.
Use this method to store locally without a database.
The page to use is globals.dart with bool variable, button.dart which is the page selection window (change button color when bookmarked),
And there is a file home0_01.dart with a "favorite icon button (click to add that button to favorites)".
Here I would like to implement it to be stored locally using shared_prefer
But even looking at a lot of example code, it's hard to implement.
There are hundreds of favoriteButton_0_01 in my code because there are so many home0_01.dart files. How should I code in this case?
globals.dart
library prj.com.globals;
bool favoriteButton_0_01 = true;
bool favoriteButton_0_02 = false;
...
button.dart
...
LearnLevelButton(
color: favoriteButton_0_01 ? Colors.orange : Color(0xff7ba6f9),
text: '',
onTap: () async {
await Navigator.pushReplacement(context, MaterialPageRoute(builder: (context){
return home0_01();
}));
},
),
...
home0_01.dart
void delete() async {
setState(() {
favoriteButton_0_01 = false;
print(favoriteButton_0_01);
});
}
void saved() async {
setState(() {
favoriteButton_0_01 = true;
print(favoriteButton_0_01);
});
}
...
actions: <Widget>[
IconButton(
onPressed: favoriteButton_0_01 ? delete : saved,
icon: favoriteButton_0_01
? Icon(Icons.bookmark_rounded, color: Colors.yellow[800], size: 30)
: Icon(Icons.bookmark_add_outlined, color: Colors.yellow[800],size: 30),
),
],
...
You can watch this tutorial in order to accomplish something like that: https://www.youtube.com/watch?v=TRB0qZ2XaO4. It's basically the same idea. Press a button and add it somewhere else. Hope this might help.

Perform in app force update using current and required build numbers

I want to force update my app.
Here's what I have done so far.
Obtained the current build version of my app using package_info_plus
Obtained the enforced build version which I have stored in the firebase remote config. So I used this package: firebase_remote_config
I then compared the two build numbers to see if the update is needed. What should I do after that?
Here's my code:
void initState(){
super.initState();
checkForUpdate();
_initPackageInfo();
_enforcedVersion();
if(int.parse(_packageInfo.buildNumber) > int.parse(enforcedBuildNumber))
{
//How to force update?
}
}
Future<void> _initPackageInfo() async {
final info = await PackageInfo.fromPlatform();
setState(() {
_packageInfo = info;
});
}
Future<void> _enforcedVersion() async {
final RemoteConfig remoteConfig = RemoteConfig.instance;
await remoteConfig.setConfigSettings(RemoteConfigSettings(
fetchTimeout: const Duration(seconds: 10),
minimumFetchInterval: Duration.zero,
));
await remoteConfig.fetchAndActivate();
setState(() {
enforcedBuildNumber = remoteConfig.getString('enforced_build_number');
});
}
You could display a non dismissable dialog which would ask the user to update the application with a redirection button to the device appstore.
By using a package such as url_launcher you can easily do that:
Code Sample
import 'dart:io' show Platform;
import 'package:url_launcher/url_launcher.dart';
// You can show a dialog like this
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => AlertDialog(
title: Text('Please update your app'),
actions: [
TextButton(
onPressed: launchAppStore,
child: Text('Open App Store'),
),
],
),
);
// Method to open the appstore
void launchAppStore() {
/// Depending on where you are putting this method you might need
/// to pass a reference from your _packageInfo.
final appPackageName = _packageInfo.packageName;
if (Platform.isAndroid) {
launch("https://play.google.com/store/apps/details?id=$appPackageName");
} else if (Platform.isIOS) {
launch("market://details?id=$appPackageName");
}
}

Flutter exception: 'Context is not a subtype of BuildContext' error using Navigator

I am working on a flutter app and I am running into the following error: "The argument type 'Context' can't be assigned to the parameter type 'BuildContext'." However, when I try to pass in context to my functions as it says to do on the internet, I am unable to get it to work. Can someone please help me with this? The app is a camera app, and I know the video is successfully being recorded. here is the code:
This is the stop button that is pressed.
IconButton(
icon: const Icon(Icons.stop),
color: Colors.red,
onPressed: () {controller != null &&
controller.value.isInitialized &&
controller.value.isRecordingVideo
? onStopButtonPressed. //this is the function that is being called
: null;},
) //icons.stop
This is where the app isn't working with my Navigator.push call. It works fine when I take it out.
void onStopButtonPressed() {
stopVideoRecording().then((_) {
if (mounted) setState(() {});
print('Video recorded to: $videoPath');
print('Navigator is hit');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PreviewImageScreen(videoPath: videoPath),
), //MaterialpageRoute
); //Navigator
});
}
And here is my stopVideoRecording function
Future<void> stopVideoRecording() async {
if (!controller.value.isRecordingVideo) {
return null;
}
try {
await controller.stopVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
//await _startVideoPlayer();
}
Thanks!
change it to
Navigator.push(
this.context, //add this so it uses the context of the class
MaterialPageRoute(
builder: (context) => PreviewImageScreen(videoPath: videoPath),
), //MaterialpageRoute
); //Navigator
Maybe you're importing a library or something that has a class named context and is interfering with the name context

No implementation found for method scan on channel flutter com.apptresoftwore.barcode_scan

I tried to create a QRCode scanner in my mobile application using Flutter.I add the package barcode_scan in pubspec.yaml and the permission to the camera
But everytime the same error was showed that no imlimentation found for method scan i can't found the solution.this is my code
import 'package:flutter/material.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'dart:async';
import 'package:flutter/services.dart';
class MyHomePage extends StatefulWidget{
#override
_MyHomePageState createState()=> new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String result = "Hey there !";
Future _scanQR() async {
try {
String qrResult = await BarcodeScanner.scan();
setState(() {
result = qrResult;
});
} on PlatformException catch (ex) {
if (ex.code == BarcodeScanner.CameraAccessDenied) {
setState(() {
result = "Camera permission was denied";
});
} else {
setState(() {
result = "Unknown Error $ex";
});
}
} on FormatException {
setState(() {
result = "You pressed the back button before scanning anything";
});
} catch (ex) {
setState(() {
result = "Unknown Error $ex";
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("QR Scanner"),
),
body: Center(
child: Text(
result,
style: new TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold),
),
),
floatingActionButton: FloatingActionButton.extended(
icon: Icon(Icons.camera_alt),
label: Text("Scan"),
onPressed: _scanQR,
),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerFloat,
);
}
}
The error "No implementation found for method..." is usually caused when Flutter is unable to find the method called from the package due to the plugin not being properly added to the project. The same issue can also be encountered if the plugin used doesn't support the targeted platform. But since barcode_scan plugin seems to support both iOS and Android, this may have been caused by the former.
You can try running flutter pub get to verify that the plugins have been added to the project and run the app using full restart to ensure that all packages added are compiled.
I've also noticed that barcode_scan has been discontinued as of this writing. The plugin may still work as expected, but it won't be receiving further updates from its developers. You can also check other barcode scanner plugins from pub.dev that may fit your use case.