Home > Net >  Flutter, StaggeredGridView is not showing until i press hot Reload | Tried several options but none
Flutter, StaggeredGridView is not showing until i press hot Reload | Tried several options but none

Time:06-08

i have this problem where my StaggeredGridView is not showing until i press HotReload. I've already tried and looked up different solutions but haven't managed to solve the problem. I know the Problem is that the widget is built before initializing the data in the GridView but i don't know how to solve this. I would be very grateful for any help

PS: I'm new to Flutter.

Here My Code for the StaggeredGridView

import 'package:festival/Utils/DatabaseService.dart';
import 'package:festival/Utils/FestivalItem.dart';
import 'package:festival/Utils/FestivalItemDetails.dart';
import 'package:festival/Utils/FestivalItemDistance.dart';
import 'package:festival/provider/location_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class HomePageWidget extends StatefulWidget {
  const HomePageWidget({Key? key}) : super(key: key);

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

class _HomePageWidgetState extends State<HomePageWidget> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color.fromRGBO(26, 31, 36,80),
        automaticallyImplyLeading: false,
        title: Text(
          'Festivals',
          style: TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.w600, fontFamily: 'Poppins'),
          textAlign: TextAlign.center,
        ),
        actions: [],
        centerTitle: false,
        elevation: 2,
      ),
      backgroundColor: Color.fromRGBO(26, 31, 36,80),
      body: SafeArea(
            child: FutureBuilder(
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if(snapshot.hasData){
                return Container(
                  child: StaggeredGridView.countBuilder(
                    crossAxisCount: 4,
                    itemCount: oDB.destinationsList.length,
                    physics: ScrollPhysics(),
                    mainAxisSpacing: 16,
                    crossAxisSpacing: 16,
                    itemBuilder: (context, index) => GestureDetector(child: FestivalItem(oDB.destinationsList[index]),
                        onTap:(){
                          Navigator.push(
                              context,MaterialPageRoute(
                                  builder: (context)=>
                                      FestivalItemDetails(oDB.destinationsList[index])
                          )
                          );}
                    ),
                    staggeredTileBuilder: (index) => StaggeredTile.count(
                        (index % 7 == 0) ? 2 : 1, (index % 7 == 0) ? 2 : 1),
                  ),
                );}
                else{
                  return CircularProgressIndicator();
                }
              }
            )
        ), 
      );
  }
}

And here is my Databaseservice where i fetch my Data from Firestore

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:festival/Utils/Destination.dart';
import 'package:geolocator/geolocator.dart';

/// Again, application-level global variable
DatabaseService oDB = new DatabaseService();

class DatabaseService {
  static final DatabaseService _oDB = new DatabaseService._internal();

  // the list of events
  List<Destination> destinationsList = [];

  /// create Database
  factory DatabaseService() {
    return _oDB;
  }

  /// initialize properties
  DatabaseService._internal() {}

  //Convert Future list to list
  Future<void> convertList() async {
    Future<List<Destination>> newDestinations = DatabaseService().getDestinations();
    Future<List> _futureOfList = newDestinations;
    List _destinations = await _futureOfList;
    print(_destinations);
    destinationsList = _destinations.cast<Destination>();
  }

  //Calculate distance between user location and festival location
  distanceCalculator(Position position) async {
    for (var i = 0; i < oDB.destinationsList.length; i  ) {
      var m = Geolocator.distanceBetween(
        position.latitude,
        position.longitude,
        oDB.destinationsList.elementAt(i).lat,
        oDB.destinationsList.elementAt(i).long,
      );

      var d = m / 1000;
      oDB.destinationsList.elementAt(i).distance = d;
    }
    oDB.destinationsList.sort((a, b) {
      return a.distance.compareTo(b.distance);
    });
    return oDB.destinationsList;
  }

  //A reference to the List of Destinations
  final destinationRef = FirebaseFirestore.instance.collection('festivals').withConverter<Destination>(
        fromFirestore: (snapshot, _) => Destination.fromJson(snapshot.data()!),
        toFirestore: (destination, _) => destination.toJson(),
      );

  //Get Data in a List
  Future<List<Destination>> getDestinations() async {
    final querySnapshot = await FirebaseFirestore.instance.collection('festivals').get();
    List<QueryDocumentSnapshot> docs = querySnapshot.docs;
    final destinationList = docs.map((doc) => Destination.fromJson(doc.data() as Map<String, dynamic>)).toList();
    return destinationList;
  }

}

CodePudding user response:

As per my knowledge pleas check oDB.destinationsList.length in this you get data or not at run time.

CodePudding user response:

    import 'package:festival/Utils/DatabaseService.dart';
    import 'package:festival/Utils/FestivalItem.dart';
    import 'package:festival/Utils/FestivalItemDetails.dart';
    import 'package:festival/Utils/FestivalItemDistance.dart';
    import 'package:festival/provider/location_provider.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
    
    class HomePageWidget extends StatefulWidget {
      const HomePageWidget({Key? key}) : super(key: key);
    
      @override
      _HomePageWidgetState createState() => _HomePageWidgetState();
    }
    
    class _HomePageWidgetState extends State<HomePageWidget> {

List listData=[];
  @override
  void initState() {

    super.initState();
listData=oDB.destinationsList;
}
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Color.fromRGBO(26, 31, 36,80),
            automaticallyImplyLeading: false,
            title: Text(
              'Festivals',
              style: TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.w600, fontFamily: 'Poppins'),
              textAlign: TextAlign.center,
            ),
            actions: [],
            centerTitle: false,
            elevation: 2,
          ),
          backgroundColor: Color.fromRGBO(26, 31, 36,80),
          body: SafeArea(
                child: FutureBuilder(
                  builder: (BuildContext context, AsyncSnapshot snapshot) {
                    if(listData.length != 0){
                    return Container(
                      child: StaggeredGridView.countBuilder(
                        crossAxisCount: 4,
                        itemCount: oDB.destinationsList.length,
                        physics: ScrollPhysics(),
                        mainAxisSpacing: 16,
                        crossAxisSpacing: 16,
                        itemBuilder: (context, index) => GestureDetector(child: FestivalItem(oDB.destinationsList[index]),
                            onTap:(){
                              Navigator.push(
                                  context,MaterialPageRoute(
                                      builder: (context)=>
                                          FestivalItemDetails(oDB.destinationsList[index])
                              )
                              );}
                        ),
                        staggeredTileBuilder: (index) => StaggeredTile.count(
                            (index % 7 == 0) ? 2 : 1, (index % 7 == 0) ? 2 : 1),
                      ),
                    );}
                    else{
                      return CircularProgressIndicator();
                    }
                  }
                )
            ), 
          );
      }
    }

try this code.

  • Related