Click here to Skip to main content
15,352,155 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
My app screen does not change the state of it in real-time while updated in the firebase real-time database .. the earnings screen is updated after the driver ends the trip and collects the fares of the trip then updated total earnings and number of total trips and the history of trips .. I want a solution

Earnings class

Dart
import 'package:drivers_app/Data_Handler/app_Data.dart';
import 'package:drivers_app/modules/history_screen.dart';
import 'package:drivers_app/shared/components/components.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class EarningsScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Column
    (
      children:
      [
        Container(
          color: Colors.black87,
          width: double.infinity,
          child: Padding(
              padding: EdgeInsets.symmetric(vertical: 50.0),
              child: Column(
                children:
                [
                  Text("Total Earnings", style: TextStyle(fontSize: 18.0 ,color: Colors.white),),
                  SizedBox(height: 30.0,),
                  Text("${Provider.of<AppData>(context, listen: false).earnings} L.E", style: TextStyle(color: Colors.white, fontSize: 50),),
                ],
              ),
          ),
        ),

        MaterialButton(
            padding: EdgeInsets.all(0),
            onPressed: ()
            {
              navigateTo(context, HistoryScreen());
            },
            child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 30, vertical: 18),
              child: Row(
                children:
                [
                  Image.asset('assets/images/taxi.png', width: 70,),
                  SizedBox(width: 16.0,),
                  Text("Total Trips", style: TextStyle(fontSize: 16.0),),
                  Expanded(child: Container(child: Text(Provider.of<AppData>(context, listen: false).countTrips.toString(), textAlign: TextAlign.end, style: TextStyle(fontSize: 18.0),))),
                ],
              ),
            ),
        ),
        Divider(height: 2.0, thickness: 2.0,),
      ],
    );
  }
}



AppData class

Dart
// ignore_for_file: file_names
import 'package:drivers_app/models/address.dart';
import 'package:drivers_app/models/drivers.dart';
import 'package:drivers_app/models/history.dart';
import 'package:flutter/material.dart';

class AppData extends ChangeNotifier
{
  String earnings = "0";
  int countTrips = 0;
  Address myAddress = Address();
  List<String> tripHistoryKeys = [];
  List<History> tripHistoryDataList = [];

  void updateEarnings(String updatedEarnings)
  {
    earnings = updatedEarnings;
    notifyListeners();
  }

  void updateTripsCounter(int tripCounter)
  {
    countTrips = tripCounter;
    notifyListeners();
  }

  void updateTripsKeys(List<String> newKeys)
  {
    tripHistoryKeys = newKeys;
    notifyListeners();
  }

  void updateTripHistoryData(History eachHistory)
  {
    tripHistoryDataList.add(eachHistory);
    notifyListeners();
  }

  void updateMyAddress(Address myAddress){
    this.myAddress = myAddress;
    notifyListeners();
  }
}


MainScreen class

Dart
import 'package:drivers_app/tabsPages/earnings_tab_screen.dart';
import 'package:drivers_app/tabsPages/home_tab_screen.dart';
import 'package:drivers_app/tabsPages/profile_tab_screen.dart';
import 'package:drivers_app/tabsPages/zones_tab_page.dart';
import 'package:flutter/material.dart';

class MainScreen extends StatefulWidget
{
  static const String mainScreenId = "mainScreenId";

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

class _MainScreenState extends State<MainScreen> with SingleTickerProviderStateMixin
{
  int selectedIndex = 0;

  void onItemClicked(int index)
  {
    setState(()
    {
      selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold
    (
      body: IndexedStack(
        children:
        [
          HomeScreen(),
          EarningsScreen(),
          ZonesScreen(),
          ProfileScreen(),
        ],
        index: selectedIndex,
      ),
      bottomNavigationBar: BottomNavigationBar(
        items:<BottomNavigationBarItem>
        [
          BottomNavigationBarItem(
            icon: Icon(
                Icons.home,
              ),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(
                Icons.credit_card,
              ),
            label: 'Earnings',
          ),
          BottomNavigationBarItem(
            icon: Icon(
                Icons.settings_input_antenna_rounded,
              ),
            label: 'Zones',
          ),
          BottomNavigationBarItem(
            icon: Icon(
                Icons.person,
              ),
            label: 'Account',
          ),
        ],
        unselectedItemColor: Colors.black54,
        selectedItemColor: Colors.blue,
        type: BottomNavigationBarType.fixed,
        selectedLabelStyle: TextStyle(
          fontSize: 12.0
        ),
        showUnselectedLabels: true,
        currentIndex: selectedIndex,
        onTap: onItemClicked,

      ),
    );
  }
}



History Screen class

Dart
import 'package:drivers_app/Data_Handler/app_Data.dart';
import 'package:drivers_app/shared/components/history_item.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class HistoryScreen extends StatefulWidget
{

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

class _HistoryScreenState extends State<HistoryScreen>
{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Trip History'),
        backgroundColor: Colors.black87,
        leading: IconButton(
          onPressed: ()
          {
            Navigator.pop(context);
          },
          icon: Icon(Icons.keyboard_arrow_left),
        ),
      ),
      body: ListView.separated(
          itemBuilder: (context, index)
          {
            return HistoryItem(
              history: Provider.of<AppData>(context, listen: false).tripHistoryDataList[index],
            );
          },
          separatorBuilder: (BuildContext context, int index) => Divider(thickness: 2.0, height: 3.0,),
          itemCount: Provider.of<AppData>(context, listen: false).tripHistoryDataList.length,
          physics: ClampingScrollPhysics(),
          shrinkWrap: true,
      ),
    );
  }
}



Functions class

Dart
static void retrieveHistoryInfo(context)
  {
    //retrieve and display Earnings
    driversRef.child(currentfirebaseUser!.uid).child("earnings").once().then((DataSnapshot dataSnapshot)
    {
      if(dataSnapshot.value != null)
      {
        String earnings = dataSnapshot.value.toString();
        Provider.of<AppData>(context, listen: false).updateEarnings(earnings);
      }
    });

    //retrieve and display Trip History
    driversRef.child(currentfirebaseUser!.uid).child("history").once().then((DataSnapshot dataSnapshot)
    {
      if(dataSnapshot.value != null)
      {
        //update total number of trip counts to provide
        Map<dynamic, dynamic> keys = dataSnapshot.value;
        int tripCounter = keys.length;
        Provider.of<AppData>(context, listen: false).updateTripsCounter(tripCounter);

        //update trip keys to provider
        List<String> tripHistoryKeys = [];
        keys.forEach((key, value) 
        {
          tripHistoryKeys.add(key);
        });
        Provider.of<AppData>(context, listen: false).updateTripsKeys(tripHistoryKeys);
        obtainTripRequestHistoryData(context);
      }
    });

  }

  static obtainTripRequestHistoryData(context)
  {
    var keys = Provider.of<AppData>(context, listen: false).tripHistoryKeys;

    for(String key in keys)
    {
      newRequestRef.child(key).once().then((DataSnapshot snapshot)
      {
        if (snapshot.value != null)
        {
          var history = History.fromSnapshot(snapshot);
          Provider.of<AppData>(context, listen: false).updateTripHistoryData(history);
        }
      });
    }
  }

  static String formatTripDate(String date)
  {
    DateTime dateTime = DateTime.parse(date);
    String formattedDate = "${DateFormat.MMMd().format(dateTime)}, ${DateFormat.y().format(dateTime)} - ${DateFormat.jm().format(dateTime)}";
    return formattedDate;
  }


What I have tried:

I tried to change the IndexedStack of the Main class but I want a solution
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900