Home > OS >  Why is my state not initialized in flutter Consumer/Provider?
Why is my state not initialized in flutter Consumer/Provider?

Time:04-02

At the bottom of main

var nums = state.getItems();
print("nums: "   nums.toString());

nums is null, maybe I am initializing it wrong? Thank you

main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  runApp(ChangeNotifierProvider(
      create: (context) => TheState(),
      child: const MyHomePage(
        title: 'ok',
      )));
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      var state = Provider.of<TheState>(context, listen: false);
      state.dbInit();
    });
  }

  @override
  Widget build(BuildContext context) {
    return const DogList();
  }
}

class DogList extends StatelessWidget {
  const DogList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<TheState>(
      builder: (context, state, child) {
        var nums = state.getItems();
        print("nums: "   nums.toString());

TheState.dart

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

class TheState extends ChangeNotifier {
  int? items;
  Query? _feedQuery;
  final DatabaseReference kDb = FirebaseDatabase.instance.ref();
  Future<bool> dbInit() {
    try {
      _feedQuery!.onChildAdded.listen(_childAdded);
      //_feedQuery!.onChildChanged.listen(_onTweetChanged);
      initItems();
      return Future.value(true);
    } catch (error) {
      print("ERROR");
      return Future.value(false);
    }
  }

  int? getItems() {
    return items;
  }

  void initItems() {
    var calledFrom = "getItems";
    try {
      print("in try"   " "   calledFrom);
      kDb.child('tweet').once().then((DatabaseEvent event) {
        print("returned"   " "   calledFrom);
        final snapshot = event.snapshot;
        if (snapshot.value != null) {
          var map = snapshot.value as Map<dynamic, dynamic>;
          items = map.length;
        }
      }).catchError((e, stackTrace) {
        print("in catchError"   " "   calledFrom);
      }).whenComplete(() => print("COMPLETE"   " "   calledFrom));
    } catch (error) {
      print("catch"   " "   calledFrom);
    } finally {
      print("finally"   " "   calledFrom);
    }
  }

  void _childAdded(DatabaseEvent event) {}
}

CodePudding user response:

Add notifyListeners() after the you get data

void initItems() {
    var calledFrom = "getItems";
    try {
      print("in try"   " "   calledFrom);
      kDb.child('tweet').once().then((DatabaseEvent event) {
        print("returned"   " "   calledFrom);
        final snapshot = event.snapshot;
        if (snapshot.value != null) {
          var map = snapshot.value as Map<dynamic, dynamic>;
          items = map.length;
          notifyListeners();
        }
      }).catchError((e, stackTrace) {
        print("in catchError"   " "   calledFrom);
      }).whenComplete(() => print("COMPLETE"   " "   calledFrom));
    } catch (error) {
      print("catch"   " "   calledFrom);
    } finally {
      print("finally"   " "   calledFrom);
    }
  }
  • Related