-1

I have a list using flutter provider.But firestore data works.The problem is that provider. Error is the getter length was called on null. I searched this question in stackoverflow, i tried every answer but they did not solve my problem. Here is included code in bellow :

GameServices Class

class GamesServices {
  String collection = 'games';
  Firestore _firestore = Firestore.instance;

  Future<List<GamesModel>> getGames() async {
    _firestore.collection(collection).getDocuments().then((result) {
      List<GamesModel> gameList = <GamesModel>[];
      for (DocumentSnapshot game in result.documents) {
        gameList.add(GamesModel.fromSnapshot(game));
      }
      return gameList;
    });
  }

Provider Class

class BoshphelmProvider with ChangeNotifier {
  GamesServices _gamesServices = GamesServices();
  List<GamesModel> _games = <GamesModel>[];

  List<GamesModel> get games => _games;

  BoshphelmProvider.initialize() {
    loadGames();
  }

  loadGames() async {
    _games = await _gamesServices.getGames();
    notifyListeners();
  }
}

Main Class


void main() {
  setupLocator();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: BoshphelmProvider.initialize(),
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Boshphelm',
        theme: ThemeData(
          primaryColor: Constant.primaryColor,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: HomePage(),
      ),
    );
  }
}

1 Answers1

0

you are missing the code part where you try to get the length of something and it throws that error

without that i would guess you are trying to access games list before it finishes initializing, as you are not waiting for it

try this

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  BoshphelmProvider _provider = BoshphelmProvider();
  await _provider.initialize()
  setupLocator();
  runApp(MyApp()); 
}

class MyApp extends StatefulWidget {


@override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: _provider,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Boshphelm',
        theme: ThemeData(
          primaryColor: Constant.primaryColor,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: HomePage(),
      ),
    );
  }
}