简体   繁体   中英

Firestore with StreamBuilder

I want to use Firestore with StreamBuilder. But i get error:

No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

The relevant error-causing widget was:

Kutuphane file:///C:/Users/burak/Desktop/flutter_ornekler/mto/lib/main/main.dart:44:26

44:26 is Kutuphane _kutuphane = ( this point )Kutuphane();

I added 2 photos to the bottom. Please check it.

I added these codes but i'm getting same error:

bool USE_FIRESTORE_EMULATOR = false;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
  if (USE_FIRESTORE_EMULATOR) {
    FirebaseFirestore.instance.settings = Settings(
        host: 'localhost:8080', sslEnabled: false, persistenceEnabled: false);
  }
}

You should comment out some lines code. I didn't share irrelevant codes.

main.dart

bool USE_FIRESTORE_EMULATOR = false;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
  if (USE_FIRESTORE_EMULATOR) {
    FirebaseFirestore.instance.settings = Settings(
        host: 'localhost:8080', sslEnabled: false, persistenceEnabled: false);
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Duyurular _duyurular = Duyurular();
  Dergiler _dergiler = Dergiler();
  Anasayfa _anasayfa = Anasayfa();
  CanliDersler _canliDersler = CanliDersler();
  Kutuphane _kutuphane = Kutuphane();

  Widget _showPage = new Anasayfa();

  int _iconColorNumber = 2;
  int _iconSize = 2;

  Widget _pageChooser(int page) {
    switch (page) {
      case 0:
        return _duyurular;
        break;
      case 1:
        return _dergiler;
        break;
      case 2:
        return _anasayfa;
        break;
      case 3:
        return _canliDersler;
        break;
      case 4:
        return _kutuphane;
        break;
      default:
        return new Container(
          child: new Center(
            child: new Text(
              "Sayfa bulunamadı..",
              style: new TextStyle(fontSize: 30),
            ),
          ),
        );
    }
  }

  nested() {
    return NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverAppBar(
              toolbarHeight: 50,
              expandedHeight: 92.0,
              floating: false,
              pinned: true,
              flexibleSpace: FlexibleSpaceBar(
                background: Image.asset(
                  "assets/images/besmele.jpg",
                  fit: BoxFit.cover,
                ),
              ),
              actions: [
                IconButton(
                  icon: Icon(Icons.account_circle),
                  color: Colors.white,
                  onPressed: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => ProfilAppBarli()));
                  },
                ),
              ],
            )
          ];
        },
        body: Container(
          child: Center(
            child: _showPage,
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: nested(),
      drawer: Drawer(
        child: DrawerDosyasi(),
      ),
      bottomNavigationBar: CurvedNavigationBar(
        color: Colors.blue,
        backgroundColor: Colors.white,
        buttonBackgroundColor: Colors.blue,
        height: 50,
        index: 2,
        items: <Widget>[
          Icon(
            Icons.campaign,
            size: _iconSize == 0 ? 30 : 20,
            color: _iconColorNumber == 0 ? Colors.orange : Colors.white,
          ),
          Icon(
            Icons.library_books,
            size: _iconSize == 1 ? 30 : 20,
            color: _iconColorNumber == 1 ? Colors.orange : Colors.white,
          ),
          Icon(
            Icons.home,
            size: _iconSize == 2 ? 30 : 20,
            color: _iconColorNumber == 2 ? Colors.orange : Colors.white,
          ),
          Icon(
            Icons.video_collection_rounded,
            size: _iconSize == 3 ? 30 : 20,
            color: _iconColorNumber == 3 ? Colors.orange : Colors.white,
          ),
          Icon(
            Icons.menu_book_rounded,
            size: _iconSize == 4 ? 30 : 20,
            color: _iconColorNumber == 4 ? Colors.orange : Colors.white,
          ),
        ],
        animationDuration: Duration(
          milliseconds: 300,
        ),
        animationCurve: Curves.bounceInOut,
        onTap: (int tappedIndex) {
          setState(() {
            _showPage = _pageChooser(tappedIndex);
            _iconColorNumber = tappedIndex;
            _iconSize = tappedIndex;
          });
        },
      ),
    );
  }
}

kutuphane.dart

class KutuphaneAppBarli extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(
            toolbarHeight: 50,
            leading: IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: const Icon(Icons.arrow_back_rounded),
            ),
            title: Text("Kütüphane"),
            elevation: 0,
            backgroundColor: Colors.blue,
          ),
          body: Kutuphane()),
    );
  }
}

class Kutuphane extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseFirestore.instance.collection("kutuphane").snapshots(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasError) {
          return Center(
            child:
                Text("Bir şeyler ters gitti. \n Hata : \n ${snapshot.error}"),
          );
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: Text("Sayfa yükleniyor.."),
          );
        }

        return ListView(
          children: snapshot.data.docs
              .map((doc) => ListTile(
                  title: Text(doc["ListeAdi"]),
                  subtitle: Text(
                      "Okunan Kitap Sayısı : ${doc["OkunanKitapSayisi"]}")))
              .toList(),
        );
      },
    );
  }
}

pubspec.yaml

name: mto
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^0.14.3
  firebase_database: ^4.3.0
  page_transition: ^1.1.7+2
  simple_animations: ^2.2.3
  curved_navigation_bar: ^0.3.4
  provider: ^4.3.2+2
  shared_preferences: ^0.5.12+4
  flutter_launcher_icons: ^0.8.1
  firebase_core: ^0.5.2

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/images/mto_logo.png"


# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/images/
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

enter image description here

enter image description here

I solved the problem. I made the stateless widget in the "kutuphane" file stateful.

I don't know why it fixes.

class KutuphaneAppBarli extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(
            toolbarHeight: 50,
            leading: IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: const Icon(Icons.arrow_back_rounded),
            ),
            title: Text("Kütüphane"),
            elevation: 0,
            backgroundColor: Colors.blue,
          ),
          body: Kutuphane()),
    );
  }
}

class Kutuphane extends StatefulWidget {
  @override
  _KutuphaneState createState() => _KutuphaneState();
}

class _KutuphaneState extends State<Kutuphane> {
  bool _initialized = false;
  bool _error = false;

  void initializeFlutterFire() async {
    try {
      // Wait for Firebase to initialize and set `_initialized` state to true
      await Firebase.initializeApp();
      setState(() {
        _initialized = true;
      });
    } catch (e) {
      // Set `_error` state to true if Firebase initialization fails
      setState(() {
        _error = true;
      });
    }
  }

  @override
  void initState() {
    initializeFlutterFire();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (_error) {
      return Center(
        child: Text("Bir şeyler ters gitti. \n Hata : \n $_error"),
      );
    }

    if (!_initialized) {
      return Center(
        child: Text(""),
      );
    }

    return StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance
          .collection('kutuphane')
          .snapshots(includeMetadataChanges: true),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return Center(
            child:
                Text("Bir şeyler ters gitti. \n Hata : \n ${snapshot.error}"),
          );
        }

        if (!snapshot.hasData) {
          return Center(
            child: Text(""),
          );
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: Text(""),
          );
        }

        return new ListView(
          children: snapshot.data.docs
              .map((doc) => ListTile(
                  title: new Text(doc["ListeAdi"]),
                  subtitle: new Text(
                      "Okunan Kitap Sayısı : ${doc["OkunanKitapSayisi"]}")))
              .toList(),
        );
      },
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM