I asked in a previous question and about setting up Firebase (FlutterFire) to connect with Flutter app. Despite following all instructions, still not having any joy. Main.Dart is as follow-
import 'package:flutter/material.dart';
import 'package:footballcrazyquiz/routes.dart';
import 'package:footballcrazyquiz/theme.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
import 'package:footballcrazyquiz/shared/shared.dart';
import 'package:footballcrazyquiz/services/services.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const App());
}
class App extends StatefulWidget {
const App({super.key});
#override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire:
future: _initialization,
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.done) {
return StreamProvider(
create: (_) => FirestoreService().streamReport(),
catchError: (_, err) => Report(),
initialData: Report(),
child: MaterialApp(
debugShowCheckedModeBanner: true,
routes: appRoutes,
theme: appTheme
),
);
}
// Otherwise, show something whilst waiting for initialization to complete
return const MaterialApp(home: LoadingScreen());
},
);
}
}
So far, I have installed Firebase CLI, Been able to logged in and configure FlutterFire in the project. I think I have initialize it as well. When doing Flutter Run, the app loads (using IOS Simulator). However the database (cloud firestore) and Firebase is not connecting to the app. Any help or suggestions will be greatly appreciated. Thank you.
Got it working by just re-adding database data after following the steps.
Related
I have implemented a simple application using Flutter and FirebaseAuth where I want a user to sign in giving an email and a password, this application works as intended in the iOS simulators however, when I try side loading the application on to a physical iOS device I get several errors and the signing in process fails and the app doesn't continue there onwards. I've shown the code, the errors that arises and I have listed the steps that I've taken so far to mitigate this of which none has worked.
Code
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'screens/other/LoadingScreen.dart';
import 'screens/other/ErrorScreen.dart';
import 'screens/other/SignupScreen.dart';
import 'screens/other/HomeScreen.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
// This widget is the root of your application.
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<CovidHound> {
bool _initialized = false;
bool _error = false;
String _email = "";
String _password = "";
void initializeFlutterFire() async {
try {
await Firebase.initializeApp();
print("Init firebase");
setState(() {
_initialized = true;
});
} catch (e) {
print("Error init firebase:${e}");
setState(() {
_error = true;
});
}
}
Future<void> onTapSignIn() async {
try {
await FirebaseAuth.instance
.signInWithEmailAndPassword(email: _email, password: _password);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
} catch (e) {
print("Error signing in: $e");
}
if (FirebaseAuth.instance.currentUser != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomeScreen(),
fullscreenDialog: true,
),
);
}
}
#override
void initState() {
super.initState();
initializeFlutterFire();
}
#override
Widget build(BuildContext context) {
if(_error) {
return ErrorScreen();
}
if (!_initialized) {
return LoadingScreen();
}
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
children: [
TextField(
decoration: InputDecoration(hintText: "Email"),
onChanged: (value) {
_email = value;
},
),
TextField(
decoration: InputDecoration(hintText: "Password"),
onChanged: (value) {
_password = value;
},
),
TextButton(
onPressed: () {
onTapSignIn();
},
child: Text("Sign In"),
),
],
),
),
),
);
}
}
Errors
So far I have tried the following,
Properly configuring Firebase according to the documentation.
Cleaning Xcode workspace and builds using flutter clean.
Updating iOS and Xcode to latest versions.
Upgrading Flutter.
Adding permissions for Privacy - Local Network Usage Description in the info.plist as demonstrated in ( https://flutter.dev/docs/development/add-to-app/ios/project-setup#local-network-privacy-permissions )
Currently, you do not await your initializeFlutterFire() function, which could lead to your error message, because the subsequent code is executed before the initializing of Firebase.
Move your initializeFlutterFire() outside the MyApp or it's State class, then try to change the return type to Future<void>, then call this function in main() (instead of in initState()) for example:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await initializeFlutterFire();
runApp(MyApp());
}
Firebase (FlutterFire) requires you to initialise the plugin before you start your App's instance to avoid errors like this.
As you can see in the pics, when I try to double click in the text field to show the copy paste dialogue, it show this issue, in the terminal it says
'
══════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The getter 'pasteButtonLabel' was called on null.
Receiver: null
Tried calling: pasteButtonLabel
The relevant error-causing widget was:
MaterialApp file:///Users/home/Desktop/the%20authentic%20home%20final/theauthentichome/lib/main.dart:136:22
════════════════════════════════════════════════════════════════════════════════════════════════════'
May you have a look at the following pics to have a better understanding about the issue.
The main.dart file :
'import 'dart:async';
import 'dart:io';
import 'package:admob_flutter/admob_flutter.dart';
import 'package:flutterstore/config/router.dart' as router;
import 'package:dynamic_theme/dynamic_theme.dart';
import 'package:flutterstore/provider/ps_provider_dependencies.dart';
import 'package:flutterstore/viewobject/common/language.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/single_child_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutterstore/config/ps_theme_data.dart';
import 'package:flutterstore/provider/common/ps_theme_provider.dart';
import 'package:flutterstore/repository/ps_theme_repository.dart';
import 'package:flutterstore/utils/utils.dart';
import 'package:easy_localization/easy_localization.dart';
import 'config/ps_colors.dart';
import 'config/ps_config.dart';
import 'db/common/ps_shared_preferences.dart';
Future<void> main() async {
// add this, and it should be the first line in main method
WidgetsFlutterBinding.ensureInitialized();
final FirebaseMessaging _fcm = FirebaseMessaging();
if (Platform.isIOS) {
_fcm.requestNotificationPermissions(const IosNotificationSettings());
}
final SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getString('codeC') == null) {
await prefs.setString('codeC', null);
await prefs.setString('codeL', null);
}
Admob.initialize(Utils.getAdAppId());
//check is apple signin is available
await Utils.checkAppleSignInAvailable();
runApp(EasyLocalization(
path: 'assets/langs',
startLocale: PsConfig.defaultLanguage.toLocale(),
supportedLocales: getSupportedLanguages(),
child: PSApp()));
}
List<Locale> getSupportedLanguages() {
final List<Locale> localeList = <Locale>[];
for (final Language lang in PsConfig.psSupportedLanguageList) {
localeList.add(Locale(lang.languageCode, lang.countryCode));
}
print('Loaded Languages');
return localeList;
}
class PSApp extends StatefulWidget {
#override
_PSAppState createState() => _PSAppState();
}
Future<dynamic> initAds() async {
if (PsConfig.showAdMob && await Utils.checkInternetConnectivity()) {
// FirebaseAdMob.instance.initialize(appId: Utils.getAdAppId());
}
}
class _PSAppState extends State<PSApp> {
Completer<ThemeData> themeDataCompleter;
PsSharedPreferences psSharedPreferences;
#override
void initState() {
super.initState();
}
Future<ThemeData> getSharePerference(
EasyLocalization provider, dynamic data) {
Utils.psPrint('>> get share perference');
if (themeDataCompleter == null) {
Utils.psPrint('init completer');
themeDataCompleter = Completer<ThemeData>();
}
if (psSharedPreferences == null) {
Utils.psPrint('init ps shareperferences');
psSharedPreferences = PsSharedPreferences.instance;
Utils.psPrint('get shared');
psSharedPreferences.futureShared.then((SharedPreferences sh) {
psSharedPreferences.shared = sh;
Utils.psPrint('init theme provider');
final PsThemeProvider psThemeProvider = PsThemeProvider(
repo: PsThemeRepository(psSharedPreferences: psSharedPreferences));
Utils.psPrint('get theme');
final ThemeData themeData = psThemeProvider.getTheme();
themeDataCompleter.complete(themeData);
Utils.psPrint('themedata loading completed');
});
}
return themeDataCompleter.future;
}
List<Locale> getSupportedLanguages() {
final List<Locale> localeList = <Locale>[];
for (final Language lang in PsConfig.psSupportedLanguageList) {
localeList.add(Locale(lang.languageCode, lang.countryCode));
}
print('Loaded Languages');
return localeList;
}
#override
Widget build(BuildContext context) {
// init Color
PsColors.loadColor(context);
return MultiProvider(
providers: <SingleChildWidget>[
...providers,
],
child: DynamicTheme(
defaultBrightness: Brightness.light,
data: (Brightness brightness) {
if (brightness == Brightness.light) {
return themeData(ThemeData.light());
} else {
return themeData(ThemeData.dark());
}
},
themedWidgetBuilder: (BuildContext context, ThemeData theme) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'مفرشي',
theme: theme,
initialRoute: '/',
onGenerateRoute: router.generateRoute,
localizationsDelegates: <LocalizationsDelegate<dynamic>>[
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
EasyLocalization.of(context).delegate,
],
supportedLocales: EasyLocalization.of(context).supportedLocales,
locale: EasyLocalization.of(context).locale,
);
}));
}
}'
images for references:
the iOS device error message
the terminal code message
A quick Google search suggests that this might be connected to the available localisations. Have you tried adding DefaultCupertinoLocalizations.delegate to your localizationsDelegates in MaterialApp?
(This is just a wild guess, may very well be that it's no use...)
my question is whether I have to do any additional steps in order to get a list of available cameras on iOS.
Even when following the docs and trying examples from other online resources, I can't seem to get a list of available cameras.
Here's the code. It's super basic but still doesn't give me any cameras.
dependencies:
flutter:
sdk: flutter
camera:
I've placed the dependency in the pubspec.yaml file
Performing hot restart...
Restarted application in 1,146ms.
flutter: []
The output is simply an empty array.
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
void main() => runApp(CameraApp());
class CameraApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: CameraScreen(),
);
}
}
class CameraScreen extends StatefulWidget {
#override
_CameraScreenState createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen> {
#override
void initState() {
super.initState();
availableCameras().then((availableCameras) {
print(availableCameras);
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Text('Hello, World'),
),
),
);
}
}
Any ideas on what I'm doing wrong?
Thanks
I'm writing a Flutter app which only has a Google Sign In based on firebase_auth and google_sign_in. I'm unable to find a standard working example of how to mock the dependencies in Flutter or how to click the Google Authentication Dialog or bypass the whole authentication workflow.
I'm using flutter_driver for writing Integration test as mentioned here.
app_test.dart
import 'package:flutter_driver/driver_extension.dart';
import 'package:pruoo_app/main.dart' as app;
void main() {
enableFlutterDriverExtension();
app.main();
}
login.dart
//...imports
class LoginView extends StatefulWidget {
#override
_LoginViewState createState() => _LoginViewState();
}
class _LoginViewState extends State<LoginView> {
StreamSubscription<AuthenticationState> x;
void getStream(AuthenticationState state, BuildContext context) async {
if (state.toString() == 'AuthenticationAuthenticated') {
print("Navigate to Main Page");
);
}
}
Widget build(BuildContext context) {
final AuthenticationBloc authenticationBloc =
BlocProvider.of<AuthenticationBloc>(context);
x = authenticationBloc.state.listen((state) {
getStream(state, context);
});
return Scaffold(
body: Center(
child: GoogleSignInButton(
onPressed: () {
authenticationBloc.dispatch(LoggedIn());
},
)));
}
}
I am developing an App in flutter specifically for iOS (at this stage) and I need to add PDF file(s) to it. The problem is that flutter has no native way to display PDF files (as far as I researched).
From this tread it looks like it shouldn't it be too difficult to add PDF support to iOS devices using this plugin. However, I am still confused about how exactly to integrate it into my Flutter Application.
Any help would be appreciated!
When I was implementing the functionality for PDF viewer, there was no PDF plugin.
However, funny enough a friend at work found out that there is already a PDF viewer implemented for Flutter here, which we ended up using.
Note: At the time of writing the question, 16.08 there was not yet any plugin available. The mentioned was created on 30.08.
If you are looking for quick and easy way to display PDF, this might be the one.
pdf_flutter
Load PDF from network:
PDF.network(
'https://raw.githubusercontent.com/FlutterInThai/Dart-for-Flutter-Sheet-cheet/master/Dart-for-Flutter-Cheat-Sheet.pdf',
height: 500,
width: 300,
)
Load PDF from files:
File fileName;
PDF.file(
fileName,
height: 200,
width: 100,
)
Load PDF from assets:
PDF.assets(
"assets/pdf/demo.pdf",
height: 200,
width: 100,
)
add the dependencies in the pubspec.yaml
pubspec.yaml
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
pdf_viewer_plugin: ^1.0.0+2
path_provider: ^1.6.1
http: ^0.12.0+4
main.dart
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:pdf_viewer_plugin/pdf_viewer_plugin.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String path;
#override
initState() {
super.initState();
}
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/teste.pdf');
}
Future<File> writeCounter(Uint8List stream) async {
final file = await _localFile;
// Write the file
return file.writeAsBytes(stream);
}
Future<Uint8List> fetchPost() async {
final response = await http.get(
'https://expoforest.com.br/wp-content/uploads/2017/05/exemplo.pdf');
final responseJson = response.bodyBytes;
return responseJson;
}
loadPdf() async {
writeCounter(await fetchPost());
path = (await _localFile).path;
if (!mounted) return;
setState(() {});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
if (path != null)
Container(
height: 300.0,
child: PdfViewer(
filePath: path,
),
)
else
Text("Pdf is not Loaded"),
RaisedButton(
child: Text("Load pdf"),
onPressed: loadPdf,
),
],
),
),
),
);
}
}
there working code -
Add this plugin to pubspec.yaml -
>> flutter_full_pdf_viewer: ^1.0.6
on alert dialog positive button click I redirecting to view pdf -
Future<void> onPositiveButtonClick() async {
String _filePath = '';
String _directory = await ExtStorage.getExternalStoragePublicDirectory(ExtStorage.DIRECTORY_DOWNLOADS);
//todo geeting right directory path here
print("directory" + _directory);
_filePath = '$_directory/$fileName';
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => ActivityPdfView(_filePath)));
}
and this is my Activitypdfview to show pdf -
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_full_pdf_viewer/flutter_full_pdf_viewer.dart';
class ActivityPdfView extends StatefulWidget {
String filePath;
ActivityPdfView(String filePath){
this.filePath = filePath;
}
#override
_ActivityPdfViewState createState() => _ActivityPdfViewState();
}
class _ActivityPdfViewState extends State<ActivityPdfView> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyPDFList(widget.filePath), //call MyPDF List file
);
}
}
class MyPDFList extends StatelessWidget {
String pathPDF = "";
MyPDFList(String filePath){
this.pathPDF = filePath;
}
#override
Widget build(BuildContext context) {
return PDFViewerScaffold(
appBar: AppBar(
title: Text("Document"),
backgroundColor: Colors.deepOrangeAccent,
),
path: pathPDF
);
}
}
Depending on what's the min version your app supports, if it's iOS 11 and above, you can use PDFKit. Otherwise WebKit is also a good option.