firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.71k stars 3.97k forks source link

🐛 [firebase_core] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() when using StreamBuilder #6299

Closed vigneshksaithal closed 3 years ago

vigneshksaithal commented 3 years ago

Bug report

Describe the bug Even though I have initialized Firebase in main.dart; it shows No firebase app error when StreamBuilder is used in first/home page.

Steps to reproduce

  1. Clone the sample project below.
  2. Run flutter test

Expected behavior

After running flutter test there should have been no error.

Sample project

Clone this repo to reproduce error https://github.com/vigneshksaithal/error


Additional context

None.


Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand ``` Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel stable, 2.2.1, on Microsoft Windows [Version 10.0.19043.985], locale en-IN) [X] Android toolchain - develop for Android devices X 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/windows#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. [√] Chrome - develop for the web [!] Android Studio (not installed) [√] VS Code (version 1.56.2) [√] Connected device (2 available) ! Doctor found issues in 2 categories. ```

Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand ``` Dart SDK 2.13.1 Flutter SDK 2.2.1 dashboard 1.0.0+1 dependencies: - cloud_firestore 2.2.0 [cloud_firestore_platform_interface cloud_firestore_web firebase_core firebase_core_platform_interface flutter meta] - firebase_auth 1.2.0 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta] - firebase_core 1.2.0 [firebase_core_platform_interface firebase_core_web flutter meta]- flutter 0.0.0 [characters collection meta typed_data vector_math sky_engine] - url_launcher 6.0.5 [flutter meta url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows] - url_strategy 0.2.0 [flutter_web_plugins] dev dependencies: - flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters charcode collection matcher meta source_span stream_channel string_scanner term_glyph typed_data] transitive dependencies: - async 2.6.1 [meta collection] - boolean_selector 2.1.0 [source_span string_scanner] - characters 1.1.0 - charcode 1.2.0 - clock 1.1.0 - cloud_firestore_platform_interface 5.1.0 [collection firebase_core flutter meta plugin_platform_interface] - cloud_firestore_web 2.1.0 [cloud_firestore_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js] - collection 1.15.0 - fake_async 1.2.0 [clock collection] - firebase_auth_platform_interface 4.2.3 [firebase_core flutter meta plugin_platform_interface] - firebase_auth_web 1.1.3 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser intl js meta] - firebase_core_platform_interface 4.0.1 [collection flutter meta plugin_platform_interface] - firebase_core_web 1.1.0 [firebase_core_platform_interface flutter flutter_web_plugins js meta] - flutter_web_plugins 0.0.0 [flutter js characters collection meta typed_data vector_math] - http_parser 4.0.0 [charcode collection source_span string_scanner typed_data] - intl 0.17.0 [clock path] - js 0.6.3 - matcher 0.12.10 [stack_trace] - meta 1.3.0 - path 1.8.0 - plugin_platform_interface 2.0.0 [meta] - sky_engine 0.0.99 - source_span 1.8.1 [collection path term_glyph] - stack_trace 1.10.0 [path] - stream_channel 2.1.0 [async] - string_scanner 1.1.0 [charcode source_span] - term_glyph 1.2.0 - test_api 0.3.0 [async boolean_selector collection meta path source_span stack_trace stream_channel string_scanner term_glyph matcher] - typed_data 1.3.0 [collection] - url_launcher_linux 2.0.0 [flutter] - url_launcher_macos 2.0.0 [flutter] - url_launcher_platform_interface 2.0.3 [flutter plugin_platform_interface] - url_launcher_web 2.0.1 [flutter flutter_web_plugins meta url_launcher_platform_interface] - url_launcher_windows 2.0.0 [flutter] - vector_math 2.1.0 ```

main.dart

import 'package:flutter/material.dart';

import 'package:firebase_core/firebase_core.dart';
import 'package:url_strategy/url_strategy.dart';

import 'package:dashboard/app.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  setPathUrlStrategy();
  runApp(App());
}

app.dart

import 'package:flutter/material.dart';

import 'package:dashboard/routes/account.dart';
import 'package:dashboard/routes/help_and_support.dart';
import 'package:dashboard/routes/homepage.dart';
import 'package:dashboard/routes/items.dart';

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'vipatra',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => Homepage(),
        '/items': (context) => ShowItems(),
        '/help-and-support': (context) => HelpAndSupport(),
        '/account': (context) => Account(),
      },
    );
  }
}

homepage.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

import '../style.dart';

class Homepage extends StatefulWidget {
  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('vipatra'),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text(
                '',
              ),
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              leading: Icon(
                Icons.inventory,
              ),
              title: Text('Items'),
              onTap: () {
                Navigator.pushNamed(context, '/items');
              },
            ),
            ListTile(
              leading: Icon(
                Icons.reorder,
              ),
              title: Text('All Transactions'),
              onTap: () {
                // Update the state of the app.
                // ...
              },
            ),
            ListTile(
              leading: Icon(
                Icons.help_outline,
              ),
              title: Text(
                'Help & Support',
              ),
              onTap: () {
                Navigator.pushNamed(context, '/help-and-support');
              },
            )
          ],
        ),
      ),
      body: Center(
        child: Column(
          children: [
            Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(
                left: 10,
                top: 10,
                bottom: 10,
              ),
              child: Text(
                'Items',
                style: headerTextStyle,
              ),
            ),
            Expanded(
              child: Container(
                padding: EdgeInsets.only(
                  bottom: 25,
                  left: 10,
                  right: 10,
                ),
                child: Items(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Items extends StatefulWidget {
  @override
  _ItemsState createState() => _ItemsState();
}

class _ItemsState extends State<Items> {
  final Stream<QuerySnapshot<Map<String, dynamic>>> _items = FirebaseFirestore
      .instance
      .collection('biz')
      .doc('biz-id')
      .collection('items')
      .snapshots();

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: _items,
      builder: (BuildContext context,
          AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
        if (snapshot.hasError) {
          return Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text("Loading");
        }

        return ListView(
          children: snapshot.data!.docs
              .map((DocumentSnapshot<Map<String, dynamic>> document) {
            return ListTile(
              title: Text(document.data()!['item']['name']),
              subtitle: Text(document.data()!['item']['price'].toString()),
            );
          }).toList(),
        );
      },
    );
  }
}
markusaksli-nc commented 3 years ago

Hi @vigneshksaithal When just running the app there is no such error. It's unclear what you expect to happen with flutter test since you have not mentioned any test code and the repository just contains the default counter app test (which will fail anyway since this app has no counter like the default flutter create app). The error occurs because the tester just instansiates an App() without calling the main method of main.dart.

This is why it doesn't really make any sense to run the default counter test?

In any case, the plugin is working as expected here so I'm going to close the issue. Thank you

vigneshksaithal commented 3 years ago

@markusaksli-nc Oh sorry sir, I forgot to update the widget_test.dart. Now I updated in https://github.com/vigneshksaithal/error

And I am new to programming, sir you said

The error occurs because the tester just instansiates an App() without calling the main method of main.dart.

But, how to call main before App in widget_test.dart ?

My current code looks lite this.

widget_test.dart

import 'package:dashboard/app.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('Demo test', (WidgetTester tester) async {
    await tester.pumpWidget(App());

      // demo test
      expect(find.text('0'), findsNothing);
  });
}

In the test file currently I am not testing anything. But, by next week I am adding tests.

markusaksli-nc commented 3 years ago

You can just use the test setup phase to set up your firebase app