Firestore not being recognised in my flutter project - dart

Here is the error i keep recieving
E/flutter ( 6966): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
I am using
firebase_core: ^2.3.0
cloud_firestore: ^4.1.0
`
import 'package:cloud_firestore/cloud_firestore.dart';
class ChatScreen extends StatelessWidget {
const ChatScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 10,
itemBuilder: (ctx, index) => Container(
padding: const EdgeInsets.all(8),
child: const Text('This Works!'),
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () async {
FirebaseFirestore.instance
.collection('chats/oL5gfG02AjjBZ756iUT3/messages')
.snapshots()
.listen((event) {
print(event);
});
},
),
);
}
}
`

Inside the main, you should call await Firebase.initializeApp() like this
void main() async {
await Firebase.initializeApp();
runApp(const MyApp());
}
Happy coding:)

Related

local notification in flutter got "PlatformException" / need an example of local notification

Error:- Unhandled Exception: PlatformException(invalid_sound, The resource notification could not be found. Please make sure it has been added as a raw resource to your Android head project., null, null)
I am trying a lot but every time got different errors, how I learn about local notification, please suggest something as an example.
Main class
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'noti.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
void initState(){
super.initState();
Notifications.initialize(flutterLocalNotificationsPlugin);
}
#override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFF3ac3cb), Color(0xFFf85187)])),
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
backgroundColor: Colors.blue.withOpacity(0.5),
),
body: Center(
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20)
),
width: 200,
height: 80,
child: ElevatedButton(
onPressed: (){
Notifications.showBigTextNotification(title: "New message title", body: "Your long body", fln: flutterLocalNotificationsPlugin);
}, child: Text("click"),
),
),
)),
);
}
}
Notification Class
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class Notifications{
static Future initialize(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
var androidInitialize = new AndroidInitializationSettings('mipmap/ic_launcher');
//var iOSInitialize = IOSInitializationSettings();
var initializationsSettings = new InitializationSettings(android: androidInitialize,
//iOS: iOSInitialize
);
await flutterLocalNotificationsPlugin.initialize(initializationsSettings );
}
static Future showBigTextNotification({var id =0,required String title, required String body,
var payload, required FlutterLocalNotificationsPlugin fln
} ) async {
AndroidNotificationDetails androidPlatformChannelSpecifics =
new AndroidNotificationDetails(
'2',
'channel_name',
playSound: true,
sound: RawResourceAndroidNotificationSound('notification'),
importance: Importance.max,
priority: Priority.high,
);
var not= NotificationDetails(android: androidPlatformChannelSpecifics,
//iOS: IOSNotificationDetails()
);
await fln.show(0, title, body,not );
}
}

Flutter iOS app has extra ordinary padding from top and bottom / displays inside a box

When I run my flutter app for in iOS (both emulator and physical device), the app is displayed with huge padding from top and bottom. This only happens in iOS, the same app for android runs fine with the normal usual layout. All the app here is limited to this area in the display. I didn't define any padding for app in the code. What is the reason for this?
Here's the code in relevant screen;
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:instagram_clone_flutter/screens/register_screen.dart';
import 'package:instagram_clone_flutter/screens/signup_screen.dart';
import 'package:instagram_clone_flutter/utils/colors.dart';
import 'package:instagram_clone_flutter/utils/global_variable.dart';
import 'package:instagram_clone_flutter/widgets/post_card.dart';
class FeedScreen extends StatefulWidget {
const FeedScreen({Key? key}) : super(key: key);
#override
State<FeedScreen> createState() => _FeedScreenState();
}
class _FeedScreenState extends State<FeedScreen> {
#override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor:
width > webScreenSize ? webBackgroundColor : mobileBackgroundColor,
appBar: width > webScreenSize
? null
: AppBar(
backgroundColor: mobileBackgroundColor,
centerTitle: false,
title: Text("Iron Capital"),
/*SvgPicture.asset(
'assets/ic_instagram.svg',
color: primaryColor,
height: 32,
),*/
actions: [
IconButton(
icon: const Icon(
Icons.person_add_alt_1_sharp,
color: primaryColor,
),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const RegisterScreen(),
),
);
},
),
],
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('posts').snapshots(),
builder: (context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (ctx, index) => Container(
margin: EdgeInsets.symmetric(
horizontal: width > webScreenSize ? width * 0.3 : 0,
vertical: width > webScreenSize ? 15 : 0,
),
child: PostCard(
snap: snapshot.data!.docs[index].data(),
),
),
);
},
),
);
}
}
here's the main.dart file;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:instagram_clone_flutter/providers/user_provider.dart';
import 'package:instagram_clone_flutter/responsive/mobile_screen_layout.dart';
import 'package:instagram_clone_flutter/responsive/responsive_layout.dart';
import 'package:instagram_clone_flutter/responsive/web_screen_layout.dart';
import 'package:instagram_clone_flutter/screens/login_screen.dart';
import 'package:instagram_clone_flutter/utils/colors.dart';
import 'package:provider/provider.dart';
import 'package:instagram_clone_flutter/models/user.dart' as model;
import 'resources/auth_methods.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// initialise app based on platform- web or mobile
if (kIsWeb) {
await Firebase.initializeApp(
/* options: const FirebaseOptions(
apiKey: "AIzaSyCZ-xrXqD5D19Snauto-Fx_nLD7PLrBXGM",
appId: "1:585119731880:web:eca6e4b3c42a755cee329d",
messagingSenderId: "914283146786",
projectId: "instagram-clone-4cea4",
storageBucket: 'instagram-clone-4cea4.appspot.com'
),*/
);
} else {
await Firebase.initializeApp();
}
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => UserProvider(),),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Iron Capital',
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: mobileBackgroundColor,
),
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
// Checking if the snapshot has any data or not
if (snapshot.hasData) {
// final model.User user = Provider.of<UserProvider>(context).getUser;
//AuthMethods().signOut();
/*if(user.nft!.length < 2 ){
// await AuthMethods().signOut();
}*/
// if snapshot has data which means user is logged in then we check the width of screen and accordingly display the screen layout
return const ResponsiveLayout(
mobileScreenLayout: MobileScreenLayout(),
webScreenLayout: WebScreenLayout(),
);
} else if (snapshot.hasError) {
return Center(
child: Text('${snapshot.error}'),
);
}
}
// means connection to future hasnt been made yet
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return const LoginScreen();
},
),
),
);
}
}

Why I get Flutter mistake screen(red screen) when using CupertinoNavigationBarBackButton?

This is the problem that I got => The following assertion was thrown building CupertinoNavigationBarBackButton(dirty, dependencies: [_ModalScopeStatus]):
CupertinoNavigationBarBackButton should only be used in routes that can be popped
'package:flutter/src/cupertino/nav_bar.dart':
Failed assertion: line 1333 pos 9: 'currentRoute?.canPop == true'
I really do not understand this situation because I used previous 2 pages there is no problem but last page made problem.
Here is my related code part:(third page)
#override
Widget build(BuildContext context) {
final name = basename(widget.file!.path);
if(Platform.isIOS){
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
leading: CupertinoNavigationBarBackButton(
color: CupertinoColors.white,
),
This is he way how to come here:
(first page)
CupertinoButton(
padding: EdgeInsets.all(0),
child: Icon(CupertinoIcons.list_bullet, color: CupertinoColors.white,),
onPressed: () => {
Navigator.push(context, CupertinoPageRoute(builder: (context) => ConsumptionReportsScreen(location: widget.location)))
}
),
(second page)
onTap: () async {
// final file = await PDFApi.loadNetwork(reports[index].pdfUrl);
const url = 'https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf';
final file = await PDFApi().loadNetwork(url);
Navigator.push(context, CupertinoPageRoute(builder: (context) => PdfViewerScreen(file: file)));
},
The error you're getting shows that the page you're currently on can't be popped.
Failed assertion: line 1333 pos 9: 'currentRoute?.canPop == true'
Are you sure there are pages in the stack that can be popped to?
first return a material app and in and inside it use CupertionoPageScaffold() as home page , i hope this will help
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
if(Platform.isIOS){
return MaterialApp(
home: CupertinoPageScaffold(
child: Container(),
),
);
}else {
return MaterialApp(
home: Scaffold(),
);
}
}
}
Try below code, I have try other way
CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
backgroundColor: CupertinoColors.activeGreen,
middle: const Text('Sample Code'),
leading: GestureDetector(
onTap: () {
print('Button Pressed');
Navigator.of(context).pop();
},
child: Icon(
CupertinoIcons.left_chevron,
color: CupertinoColors.white,
),
),
),
child: Container(),
),
Result screen->

Error: Could not find the correct ScopedModel when using ScopedModel.of<MyModel>(context)

As an outsider looking into flutter state management, I liked the idea of using scoped_model for state management as recommended in flutter.dev. I have a rewrite of the counter app running. I am able to access the model properties using ScopedModelDescendant<CounterModel>, but I am having troubles accessing the model properties using ScopedModel.of<CounterModel>(context). Could someone please advice what I might be doing wrong? I have a hunch that it could be where the ScopedModel is in my widget tree. My code and error message follows.
main.dart
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:second/model/counter_model.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget build(context) {
return ScopedModel(
model: new CounterModel(),
child: Scaffold(
appBar: AppBar(
title: Text('ScopedModel'),
),
body: ScopedModelDescendant<CounterModel>(
builder: (context, child, value) {
return Text("Pressed ${value.counter} times");
},
),
floatingActionButton: buildFab1()),
);
}
Widget buildFab1() {
return ScopedModelDescendant<CounterModel>(
builder: (context, child, model) => FloatingActionButton(
child: Icon(Icons.add),
onPressed: model.incrementCounter,
),
);
}
Widget buildFab2(BuildContext context) {
return FloatingActionButton(
child: Icon(Icons.add),
onPressed: ScopedModel.of<CounterModel>(context).incrementCounter,
);
}
}
model/counter_model.dart
import 'package:scoped_model/scoped_model.dart';
class CounterModel extends Model {
int _counter = 0;
int get counter => _counter;
void incrementCounter() {
_counter++;
notifyListeners();
}
}
In main.dart, if I use buildFab2(context) instead of buildFab1(), I get the following error
flutter: The following ScopedModelError was thrown building ScopedModelDescendant<Model>(dirty):
flutter: Error: Could not find the correct ScopedModel.
flutter:
flutter: To fix, please:
flutter:
flutter: * Provide types to ScopedModel<MyModel>
flutter: * Provide types to ScopedModelDescendant<MyModel>
flutter: * Provide types to ScopedModel.of<MyModel>()
flutter: * Always use package imports. Ex: `import 'package:my_app/my_model.dart';
flutter:
I took a look at a few SO questions, but none helped.
Yes, that because, the context you pass will not have a ScopedModel of CounterModel.
What you can do is wrap your buildFab2 inside a Builder widget which will provide you with a context having ScopedModel with CounterModel as parent.
Like:
Builder(
builder: (context){
return buildFab2(context);
},
)
You app will look like:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget build(context) {
return ScopedModel(
model: new CounterModel(),
child: Scaffold(
appBar: AppBar(
title: Text('ScopedModel'),
),
body: ScopedModelDescendant<CounterModel>(
builder: (context, child, value) {
return Text("Pressed ${value.counter} times");
},
),
floatingActionButton: Builder(
builder: (context) {
// return buildFab1() if fab one required
return buildFab2(context);
},
),
),
);
}
Widget buildFab1() {
return ScopedModelDescendant<CounterModel>(
builder: (context, child, model) => FloatingActionButton(
child: Icon(Icons.add),
onPressed: model.incrementCounter,
),
);
}
Widget buildFab2(BuildContext context) {
return FloatingActionButton(
child: Icon(Icons.add),
onPressed: ScopedModel.of<CounterModel>(context).incrementCounter,
);
}
}
Hope that helps!
You need to add the scoppedmodel in the main.dart like this:
#override
Widget build(BuildContext context){
return ScopedModel<UserModel>(
model: UserModel(),
child: MaterialApp(
title: "Quiz Flamengo",
debugShowCheckedModeBanner: false,
home: Scaffold(
body: HomeScreen(),
)
)
);
}

Flutter, calling FutureBuilder from a raised button's onPressed doesn't call the builder property

I'm trying to learn Dart/Flutter and am working on an example where there's a button on the app that says "Get Data", and when I touch it I want to retrieve JSON data from a restful service.
I see the web service being called in fetchPost, but the builder property of the FutureBuilder isn't called.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'ResultsList.dart';
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Restul Test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: (){
FutureBuilder<ResultsList>(
future: fetchPost(),
builder: (context, snapshot){
print('In Builder');
}
);
},
child: Text('Get data'),
)
],
),
)
);
}
}
Future<ResultsList> fetchPost() async {
final response = await http.get('http://mywebserviceurl');
if (response.statusCode == 200){
print('Received data');
return ResultsList.fromJson(json.decode(response.body));
}
else {
throw Exception('Failed to load data');
}
}
Interestingly though, if I move the FutureBuilder out of the onPressed of the button to the child of Center, I do see the builder property getting called.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'ResultsList.dart';
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Restul Test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FutureBuilder<ResultsList>(
future: fetchPost(),
builder: (context, snapshot){
print ('In Builder');
return Container();
}
)
)
);
}
}
Future<ResultsList> fetchPost() async {
final response = await http.get('http://mywebserviceurl');
if (response.statusCode == 200){
print('Received data');
return ResultsList.fromJson(json.decode(response.body));
}
else {
throw Exception('Failed to load data');
}
}
Obviously I'm missing something, but any idea what I'm doing wrong?
If you want to get some data from request - you don't need FutureBuilder. You can do:
RaisedButton(
onPressed: (){
fetchPost().then((result) {
print('In Builder');
})
},
child: Text('Get data'),
)
or
RaisedButton(
onPressed: () async {
var result = await fetchPost()
print('In Builder');
},
child: Text('Get data'),
)
The onPressed method in this RaisedButton is actually not doing anything. It just creates a new FutureBuilder which does nothing but existing^^ It's like you would just call 1+1;, which just creates a value, but that value is not used to do anything.
RaisedButton(
onPressed: (){
FutureBuilder<ResultsList>(
future: fetchPost(),
builder: (context, snapshot){
print('In Builder');
}
);
},
child: Text('Get data'),
)
You could have body be assigned to a Widget(which could just be called body or whatever you want^^), which you then change in a setState((){body = FutureBuilder(/*...*/}); call.
For me FutureBuilder not working in onPresses...
I used this way :
I defined a variable in state:
bool visiblity = false;
and I used this code in build:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
visiblity=true;
fetchPost();
},
child: Text('Get data'),
),
FutureBuilder<ResultsList>(
future: ("Your View Model that return from call back"),
builder: (context, snapshot) {
if (visiblity) {
print('In Builder');
visiblity=false;
} else
return Container();
}
),
],
),
)
);
}
I didn't put FutureBuilder in onPressed. I put that in body and changed visibility after return result.

Resources