I created this test file to check for available firebase users and then move to the appropriate screen according to the response. Although I have initialized the app, it still show the error that no Firebase DEFAULT APP HAS BEEN CREATED. Call Firebase.initializeApp. Am i doing something wrong here? Also if there is any other way to check for the user being logged in or not then please tell. Keep in mind I need to fetch the data from firestore too before showing MainView().
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:splashscreen/splashscreen.dart';
import 'MainPages/LoginScreen.dart';
import 'MainPages/MainView.dart';
import 'Services/User.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
runApp(
new MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.deepOrange,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
builder: EasyLoading.init(),
home: new MyApp(),
),
);
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<Widget> loadFromFuture() async {
if (FirebaseAuth.instance.currentUser != null) {
DocumentSnapshot doc = await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser.uid)
.get();
currentUser = MyUser.fromDocument(doc);
return Future.value(new MainView());
} else {
return Future.value(new LoginScreen());
}
}
#override
Widget build(BuildContext context) {
return new SplashScreen(
navigateAfterFuture: loadFromFuture(),
title: new Text(
'Welcome In SplashScreen',
style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
image: new Image.network('https://i.imgur.com/TyCSG9A.png'),
backgroundColor: Colors.white,
styleTextUnderTheLoader: new TextStyle(),
photoSize: 100.0,
onClick: () => print("Flutter Egypt"),
loaderColor: Colors.red);
}
}
You need to await for firebase to be initialized
Please refer below code
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
runApp(MyApp());
}
Related
I want to add the permission_handler plugin. Already added it to the pubspec.yaml file, but don't know exactly where to go from there. How do I actually add the code for location permissions to my main.dart page?
main.dart page:
import 'package:flutter/material.dart';
import 'package:athena/providers/app_state.dart';
import 'package:athena/providers/user.dart';
import 'package:athena/screens/login.dart';
import 'package:athena/screens/splash.dart';
import 'locators/service_locator.dart';
import 'screens/home.dart';
import 'package:provider/provider.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
setupLocator();
return runApp(MultiProvider(
providers: [
ChangeNotifierProvider<AppStateProvider>.value(
value: AppStateProvider(),
),
ChangeNotifierProvider<UserProvider>.value(
value: UserProvider.initialize(),
),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Athena',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyApp(),
),
));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
UserProvider auth = Provider.of<UserProvider>(context);
switch (auth.status) {
case Status.Uninitialized:
return Splash();
case Status.Unauthenticated:
case Status.Authenticating:
return LoginScreen();
case Status.Authenticated:
return MyHomePage();
default:
return LoginScreen();
}
}
}
Create a function like this
Future<void> askLocationPermission() async {
await Permission.location.request();
}
Since you have added home: MyApp() as the home,
Go to MyApp(), and make it a StatefulWidget.
Then inside its initState(), call the function which requests permissions.
An example is shown below
#override
void initState() {
super.initState();
askLocationPermission();
}
I have connected my firebase project successfully because it was running and then I added other screens and changed navigation to namedRoute and now my app won't run I have received this error: "ChromeProxyService: Failed to evaluate expression 'callback': InternalError: No frame with index 14." please help
Below is my Source Code:
My main.dart file
import 'dart:ui';
import 'package:essentials/constants.dart';
// import 'package:essentials/firebase_options.dart';
import 'package:essentials/routes.dart';
import 'package:essentials/screens/splash/splash_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'screens/forgot_password/forgot_password_screen.dart';
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);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Essentials_App',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
fontFamily: "muli",
textTheme: const TextTheme(
bodyText1: TextStyle(color: kTextColor),
bodyText2: TextStyle(color: kTextColor),
),
visualDensity: VisualDensity.adaptivePlatformDensity,
primarySwatch: Colors.blue,
),
// home: SplashScreen(),
initialRoute: SplashScreen.routeName,
routes: routes,
);
}
}
Then my routes.dart and this is where i want to access my routes
import 'package:essentials/screens/signin/signin_screen.dart';
import 'package:flutter/widgets.dart';
import 'package:essentials/screens/forgot_password/forgot_password_screen.dart';
import 'package:essentials/screens/home/home_screen.dart';
import 'package:essentials/screens/login_success/login_success_screen.dart';
import 'package:essentials/screens/splash/splash_screen.dart';
import 'package:essentials/screens/signup/sign_up_screen.dart';
// All our routes will be accessed here
final Map<String, WidgetBuilder> routes = {
SplashScreen.routeName: (context) => SplashScreen(),
SignInScreen.routeName: (context) => SignInScreen(),
ForgotPasswordScreen.routeName: (context) => ForgotPasswordScreen(),
LoginSuccessScreen.routeName: (context) => LoginSuccessScreen(),
SignUpScreen.routeName: (context) => SignUpScreen(),
HomeScreen.routeName: (context) => HomeScreen(),
};
My main. dart file is where I have initialized firebase and it is where the debug is paused and it points to the initialization line of code
I tried researching about the error I found that someone had asked before and he was not answered follow this link to see his question: ChromeProxyService: Failed to evaluate expression 'FireBase.initializeApp': InternalError: No frame with index 39
can you try initialize in this way and run in web ?
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "***", // Your apiKey
appId: "***", // Your appId
messagingSenderId: "***", // Your messagingSenderId
projectId: "***", //
storageBucket: "***", // Your projectId
),
);
If you are running it in emulator may be change the emulator.
Please I want to know how to launch WhatsApp in the Flutter webview app or launch WhatsApp from the browser in Flutter, have used many codes with no errors but they do not work.Am using mac m1
and vscode
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/services/local_notification_service.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'homepage.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:colorful_safe_area/colorful_safe_area.dart';
/// Receive message when app is in background solution for on
message
Future<void> backgroundHandler(RemoteMessage message)async{
print(message.data.toString());
print(message.notification!.title);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
LocalNotificationServices.initialize();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => ConnectivityProvider(),
child: HomePage(),
)
],
child:MaterialApp(
title: 'coinpaga',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: ColorfulSafeArea(
color: HexColor("#2e2a42"),
top: true,
bottom: false,
left: false,
right: false,
child: HomePage(),
)
),
);
}
}
Home.dart
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/no_internet.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:provider/provider.dart';
class HomePage extends StatefulWidget {
// ignore: unused_field
final _flutterwebview = FlutterWebviewPlugin();
HomePage({ Key? key }) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
void initState() {
super.initState();
Provider.of<ConnectivityProvider>(context, listen:
false).startMonitoring();
}
#override
Widget build(BuildContext context) {
return pageUI();
}
#override
void dispose() {
_flutterwebview.dispose();
super.dispose();
}
}
Widget pageUI() {
return Consumer<ConnectivityProvider>(
builder: (context, model, child) {
return model.isOnline
? WebviewScaffold(
url: 'https://coinpaga.com',
withLocalStorage: true,
withJavascript: true,
scrollBar: false,
initialChild: Center(child: Text('Loading...')),
) : NoInternet();
},
);
}
// ignore: camel_case_types
class _flutterwebview {
static void dispose() {}
}
Please help me go through it.
String text = "Hello World !! Hey There";
String url = "https://wa.me/?text=${Uri.encodeFull(text)}";
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url),
mode: LaunchMode.externalApplication);
}
First, add url_launcher, then I use this code to launch whatsapp on flutter webview and works.
WebView(
initialUrl: getUrl(_url),
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (NavigationRequest request) async {
if (request.url
.startsWith('https://api.whatsapp.com/send?phone')) {
print('blocking navigation to $request}');
List<String> urlSplitted = request.url.split("&text=");
String phone = "0123456789";
String message =
urlSplitted.last.toString().replaceAll("%20", " ");
await _launchURL(
"https://wa.me/$phone/?text=${Uri.parse(message)}");
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
)
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
You can use url_launcher to launch URLs.
You can give https://api.whatsapp.com/send/?phone=(phone_number) URL to launch.
For the launching the WhatsApp Website use launch('https://api.whatsapp.com/send/?phone=(phone_number)')
Make sure you give your country code without (+).
I am new to Flutter. I want to get the text along with its source. Currently, I am using receive_sharing_intent which is serving the purpose of TextStream and Url individually.
I want to share the copied text from the browser and keep its URL along with it.
I followed this doc hence my main.dart is same as:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
StreamSubscription _intentDataStreamSubscription;
List<SharedMediaFile> _sharedFiles;
String _sharedText;
#override
void initState() {
super.initState();
// For sharing or opening urls/text coming from outside the app while the app is in the memory
_intentDataStreamSubscription =
ReceiveSharingIntent.getTextStream().listen((String value) {
setState(() {
_sharedText = value;
});
}, onError: (err) {
print("getLinkStream error: $err");
});
// For sharing or opening urls/text coming from outside the app while the app is closed
ReceiveSharingIntent.getInitialText().then((String value) {
setState(() {
_sharedText = value;
});
});
}
#override
void dispose() {
_intentDataStreamSubscription.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
const textStyleBold = const TextStyle(fontWeight: FontWeight.bold);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text("Shared files:", style: textStyleBold),
Text(_sharedFiles?.map((f)=> f.path)?.join(",") ?? ""),
SizedBox(height: 100),
Text("Shared urls/text:", style: textStyleBold),
Text(_sharedText ?? "")
],
),
),
),
);
}
}
Any suggestions on how to proceed to this or any Reference will work.
Thanks!!
I'm trying to Play a custom mp3 sound I've put in an asset folder into the app folder, like you would do for a font or an image file, but then I don't really know how to proceed. I think I might need to register the audio file into the pubspec.yaml, but how?
And how do I play it?
I've checked out this two answer:
How to play a custom sound in Flutter?
Flutter - Play custom sounds updated?
But the first one is too old and the second one uses URLs as the sound path: const kUrl2 = "http://www.rxlabz.com/labz/audio.mp3"; and the sound I like to play is in the app, not online. So... How can I do it?
This Is My Current Code, as You can see, there's only a Floating Button.
And I need To Start The Sound at the Point I stated it in the code.
But visual studio underlines in red Various Parts:
await: it says that await is unrecognized.
audioPlugin.play: is says It's also unrecognized
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());
Directory tempDir = await getTemporaryDirectory();
File tempFile = new File('${tempDir.path}/demo.mp3');
await tempFile.writeAsBytes(bytes, flush: true);
AudioPlayer audioPlugin = new AudioPlayer();
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _incrementCounter() {
setState(() {
print("Button Pressed");
///
///
///
/// Here I Need To start Playing the Sound
///
///
///
///
audioPlugin.play(tempFile.uri.toString(), isLocal: true);
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
It's not pretty, but...
Add the mp3 file to the assets folder and add it to pubspec.yaml like this.
Load the asset as binary data with rootBundle.load(asset)
Use path_provider to get the app's temp folder location
Use regular dart:io to open a file in tempDir (maybe use the asset name) and write bytes to it.
Form a file URL from the temporary file name in the form file:///folderPath/fileName
Pass this to audioplayer, setting isLocal to true (needed on iOS).
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:audioplayer/audioplayer.dart';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Audio Player Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
AudioPlayer audioPlugin = AudioPlayer();
String mp3Uri;
#override
void initState() {
_load();
}
Future<Null> _load() async {
final ByteData data = await rootBundle.load('assets/demo.mp3');
Directory tempDir = await getTemporaryDirectory();
File tempFile = File('${tempDir.path}/demo.mp3');
await tempFile.writeAsBytes(data.buffer.asUint8List(), flush: true);
mp3Uri = tempFile.uri.toString();
print('finished loading, uri=$mp3Uri');
}
void _playSound() {
if (mp3Uri != null) {
audioPlugin.play(mp3Uri, isLocal: true);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Audio Player Demo Home Page'),
),
body: Center(),
floatingActionButton: FloatingActionButton(
onPressed: _playSound,
tooltip: 'Play',
child: const Icon(Icons.play_arrow),
),
);
}
}
Use the audioplayers package => https://pub.dev/packages/audioplayers
Add the key to plist for iOS Support
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Add dependencies to pubspec.yaml file
audioplayers: ^0.13.2
Flutter code:
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
class AudioTest extends StatefulWidget {
#override
_AudioTestState createState() => _AudioTestState();
}
class _AudioTestState extends State<AudioTest> {
static AudioCache _player = AudioCache();
static const _audioPath = "count_down.mp3";
AudioPlayer _audioPlayer = AudioPlayer();
Future<AudioPlayer> playAudio() async {
return _player.play(_audioPath);
}
void _stop(){
if (_audioPlayer != null) {
_audioPlayer.stop();
}
#override
void initState() {
playAudio().then((player) {
_audioPlayer = player;
});
super.initState();
}
#override
Widget build(BuildContext context) {
return homeScreen();
}
Widget homeScreen() {
return Scaffold();
//Enter your code here
}
}