detect a change of data fetched from an api and push the the screen if it is done

0

hello everybody i'm working at driver food application and all i want do it's pushing the order_pending.dart (screen to accept the order ) when the driver received a new order.

NB: i want to push the page even that the application has closed its like messenger when you receive a call

to explain more this is how i fetch the data from api in my repository folder :

   Future<dynamic> fetchOrderListData() async {
   SharedPreferences prefs = await SharedPreferences.getInstance();
   String id = prefs.getString('id');

   final response = await http.post(
  'https:api/ws/v4/Delivery/orders.php',
   body: {'livreurID': id});

   if (response.statusCode == 200) {
   // If the server did return a 200 OK response,
  // then parse the JSON.
  var jsonResponse = null;
  jsonResponse = json.decode(response.body);
  prefs.setString(
    "orderID", (jsonResponse['Orders'][0]['orderID']));
  return OrderListData.fromJson(json.decode(response.body));
  } else {
  // If the server did not return a 200 OK response,
  // then throw an exception.
  throw Exception('Failed to load OrderListData');
  }
  }

and this is my pending order screen that I want to push it when I detect a new order from the API

 import 'dart:async';
 import 'package:deliveryman/helpers/preference_data.dart';
 import 'package:url_launcher/url_launcher.dart';
 import 'package:deliveryman/order_list_screen.dart';
 import 'package:flutter/cupertino.dart';
 import 'package:flutter/material.dart';
 import 'dart:convert';
 import 'package:deliveryman/models/order_detail.dart';
 import 'package:google_maps_flutter/google_maps_flutter.dart';
 import 'package:shared_preferences/shared_preferences.dart';
 import 'package:font_awesome_flutter/font_awesome_flutter.dart';

 import 'AnimatedPageRouteTransition.dart';
 import 'repositorys/order_repository.dart' as ordeRep;

 // Order Id geted from order_list.dar
 class OrderPending extends StatefulWidget {
 final String orderID;
 final String deliveryWishedTime;

  const OrderPending({this.orderID, this.deliveryWishedTime});

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

 class _MyAppState extends State<OrderPending> {
 Future<OrderDetailData> futureOrderDetailData;
 SharedPreferences sharedPreferences;

 GoogleMapController _mapController;

 OrderDetailData _Orderdetail;

 String _accepted = '0';
 String _userId = null;

 void _setMapStyle() async {
 String style = await DefaultAssetBundle.of(context)
    .loadString('assets/map_style.json');
  _mapController.setMapStyle(style);
 }

  void _onMapCreated(GoogleMapController controller) async {
 _mapController = controller;

 setState(() {
  _setMapStyle();
 });
 }

 @override
 void initState() {
 super.initState();
 futureOrderDetailData = ordeRep.fetchOrderDetailData(widget.orderID);
 }

 Future<String> getPref() async {
 return await PrefsUtils.getOrderDetailPref();
 }

 Future<String> setData() async {
 _userId = await PrefsUtils.getUserKeyPref();

 print("_userId : " + _userId);
 print("orderID : " + widget.orderID);
 _accepted = await ordeRep.acceptOrder(_userId, widget.orderID);
  }

 @override
 Widget build(BuildContext context) {
 return MaterialApp(
  debugShowCheckedModeBanner: false,
  theme: ThemeData.dark().copyWith(
    primaryColor: Color(0xFFE5E5E5),
    scaffoldBackgroundColor: Color(0xFFE5E5E5),
  ),
  home: Scaffold(
    backgroundColor: Color(0xFF0A0E21),
    body: FutureBuilder<OrderDetailData>(
      future: futureOrderDetailData,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Stack(
            children: [
              GoogleMap(
                initialCameraPosition: CameraPosition(
                    target: LatLng(
                        double.parse(snapshot.data.latitudeResto),
                        double.parse(snapshot.data.longitude)),
                    zoom: 13),
                onMapCreated: _onMapCreated,
                markers: {
                  Marker(
                    markerId: MarkerId('1'),
                    position: LatLng(
                        double.parse(snapshot.data.latitudeResto),
                        double.parse(snapshot.data.longitudeResto)),
                    infoWindow: InfoWindow(
                        title: snapshot.data.restoName,
                        snippet: snapshot.data.adresseResto),
                    icon: BitmapDescriptor.fromAsset('images/shop1.png'),
                  ),
                  Marker(
                    markerId: MarkerId('2'),
                    position: LatLng(double.parse(snapshot.data.latitude),
                        double.parse(snapshot.data.longitude)),
                    infoWindow: InfoWindow(
                        title: snapshot.data.clientFirstname +
                            ' ' +
                            snapshot.data.clientLastname,
                        snippet: snapshot.data.adresse),
                    icon:
                        BitmapDescriptor.fromAsset('images/customer2.png'),
                  ),
                },
                myLocationEnabled: true,
                padding: EdgeInsets.only(top: 20.0, right: 10.0),
                zoomControlsEnabled: false,
                mapToolbarEnabled: false,
              ),
              Container(
                alignment: Alignment.bottomCenter,
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: Color(0xFF0A0E21),
                  ),
                  height: 270,
                  width: MediaQuery.of(context).size.width * 0.90,
                  margin: EdgeInsets.only(bottom: 90),
                  child: Stack(
                    children: [
                      //Positioned(
                      // top:15,
                      // left: 18,
                      // child:Text(
                      // 'Etape 1 : Ramasser et verifier la commande Ref  #'+(widget.orderID) ,
                      // style: TextStyle(
                      //   fontSize: 8,
                      //   color: Color(0xff41AB7F).withOpacity(0.7),
                      //   fontFamily: 'Poppins',
                      //   fontWeight: FontWeight.bold
                      // ),
                      //  ),
                      // ),
                      Positioned(
                          left: 17,
                          top: 24,
                          child: IconButton(
                            icon: FaIcon(
                              FontAwesomeIcons.store,
                              color: Colors.white.withOpacity(0.05),
                              size: 50,
                            ),
                          )),
                      Hero(
                        tag: widget.orderID,
                        child: Container(
                          padding: EdgeInsets.all(6),
                          margin: EdgeInsets.fromLTRB(15, 20, 15, 55),
                          height: 80,
                          decoration: BoxDecoration(
                              color: Color(0xFFffffff).withOpacity(0.1),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(10))),
                          child: Container(
                            height: 80.0,
                            width: 70.0,
                            decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)),
                              image: DecorationImage(
                                image: NetworkImage(
                                    snapshot.data.restoImagePath),
                                fit: BoxFit.fill,
                              ),
                              shape: BoxShape.rectangle,
                            ),
                          ),
                        ),
                      ),
                      Positioned(
                        top: 25,
                        left: 110,
                        child: Container(
                          width: 130,
                          height: 80,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment:
                                MainAxisAlignment.spaceAround,
                            children: [
                              Text(
                                snapshot.data.restoName,
                                //overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.white,
                                  fontFamily: 'Poppins',
                                ),
                              ),
                              CircleAvatar(
                                radius: 18,
                                backgroundColor:
                                    Color(0xff41ab7f).withOpacity(0.2),
                                child: IconButton(
                                  iconSize: 15,
                                  icon: FaIcon(
                                      FontAwesomeIcons.phoneAlt,
                                      color: Color(0xff41AB7F)),
                                  onPressed: () {
                                    String RestoNumber =
                                        snapshot.data.mobileResto;
                                    launch(('tel://${RestoNumber}'));
                                  },
                                ),
                              ),
                              //Text(snapshot.data.mobileResto, style: TextStyle(fontSize: 8, color: 
                              Color(0xff41AB7F), fontFamily: 'Poppins', fontWeight: 
                              FontWeight.bold),),
                            ],
                          ),
                        ),
                      ),
                      Positioned(
                        right: 15,
                        top: 20,
                        child: Text(
                          ('+' + snapshot.data.deliveryCost),
                          style: TextStyle(
                            fontSize: 18,
                            color: Color(0xff41ab7f),
                            fontFamily: 'Poppins',
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      Positioned(
                        right: 15,
                        top: 45,
                        child: Container(
                          width: 62,
                          child: Text(
                            snapshot.data.paymentMode,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.grey.withOpacity(0.7),
                              fontFamily: 'Poppins',
                            ),
                          ),
                        ),
                      ),
                      Positioned(
                        left: 5,
                        top: 110,
                        child: IconButton(
                          icon: FaIcon(
                            FontAwesomeIcons.solidDotCircle,
                            color: Color(0xff41ab7f),
                            size: 15,
                          ),
                        ),
                      ),
                      Positioned(
                        left: 5,
                        top: 193,
                        child: IconButton(
                          icon: FaIcon(FontAwesomeIcons.crosshairs,
                              color: Color(0xff41ab7f), size: 15),
                        ),
                      ),
                      Positioned(
                        left: 5,
                        top: 130,
                        child: IconButton(
                          icon: FaIcon(FontAwesomeIcons.ellipsisV,
                              color: Color(0xff41ab7f).withOpacity(0.4),
                              size: 10),
                        ),
                      ),
                      Positioned(
                        left: 5,
                        top: 140,
                        child: IconButton(
                          icon: FaIcon(FontAwesomeIcons.ellipsisV,
                              color: Color(0xff41ab7f).withOpacity(0.4),
                              size: 10),
                        ),
                      ),
                      Positioned(
                        left: 5,
                        top: 150,
                        child: IconButton(
                          icon: FaIcon(FontAwesomeIcons.ellipsisV,
                              color: Color(0xff41ab7f).withOpacity(0.4),
                              size: 10),
                        ),
                      ),
                      Positioned(
                        left: 5,
                        top: 160,
                        child: IconButton(
                          icon: FaIcon(FontAwesomeIcons.ellipsisV,
                              color: Color(0xff41ab7f).withOpacity(0.4),
                              size: 10),
                        ),
                      ),
                      Positioned(
                        left: 5,
                        top: 170,
                        child: IconButton(
                          icon: FaIcon(FontAwesomeIcons.ellipsisV,
                              color: Color(0xff41ab7f).withOpacity(0.4),
                              size: 10),
                        ),
                      ),
                      Positioned(
                        left: 45,
                        top: 128,
                        child: Container(
                          width: 250,
                          height: 120,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment:
                                MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Pickup point :',
                                style: TextStyle(
                                    fontSize: 8,
                                    color: Color(0xff41AB7F),
                                    fontFamily: 'Poppins',
                                    fontWeight: FontWeight.bold),
                              ),
                              Text(
                                (snapshot.data.adresseResto),
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 15,
                                    color: Colors.white.withOpacity(0.6),
                                    fontFamily: 'Poppins',
                                    letterSpacing: 0.1),
                              ),
                              SizedBox(height: 45),
                              Text(
                                'Arriver Client :',
                                style: TextStyle(
                                    fontSize: 8,
                                    color: Color(0xff41AB7F),
                                    fontFamily: 'Poppins',
                                    fontWeight: FontWeight.bold),
                              ),
                              Text(
                                (snapshot.data.clientLastname +
                                    ' ' +
                                    snapshot.data.clientFirstname),
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 15,
                                    color: Colors.white.withOpacity(0.6),
                                    fontFamily: 'Poppins',
                                    letterSpacing: 0.1),
                              ),
                            ],
                          ),
                        ),
                      ),

                      Positioned(
                        bottom: 15,
                        right: 15,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(
                              'Temps souhaité',
                              style: TextStyle(
                                  fontSize: 8,
                                  color: Colors.white.withOpacity(0.6),
                                  fontFamily: 'Cairo-Regular',
                                  fontWeight: FontWeight.w400,
                                  letterSpacing: 0.4),
                            ),
                            SizedBox(
                              height: 3,
                            ),
                            Text(
                              (widget.deliveryWishedTime),
                              style: TextStyle(
                                fontSize: 25,
                                color: Colors.white,
                                fontFamily: 'Raleway-VariableFont_wght',
                              ),
                            )
                          ],
                        ),
                      ),

                      Positioned(
                        bottom: 20,
                        right: 50,
                        child: Stack(
                          children: [
                            Container(
                              height: 38,
                              width: 48,
                              child: FlatButton(
                                shape: RoundedRectangleBorder(
                                  //side: BorderSide(color: Color(0xff41ab7f)),
                                  borderRadius: BorderRadius.circular(5.0),
                                ),
                                color: Color(0xff41ab7f).withOpacity(0.2),
                                textColor: Color(0xff41ab7f),
                                splashColor: Color(0xff41ab7f),
                              ),
                            ),
                            // Positioned(
                            // left: 0,
                            // top: -5,
                            // child: IconButton(icon: FaIcon(FontAwesomeIcons.clock,color: 
                            Color(0xff41ab7f),size: 23),)
                            //child: IconButton(icon: FaIcon(FontAwesomeIcons.conciergeBell,color: 
                            Color(0xff41ab7f),size: 23),)
                            // child: IconButton(icon: FaIcon(FontAwesomeIcons.store,color: 
                            Color(0xff41ab7f),size: 23),)
                            //child: IconButton(icon: FaIcon(FontAwesomeIcons.biking, color: 
                            Color(0xff41ab7f), size: 23),)
                            // child: IconButton(icon: FaIcon(FontAwesomeIcons.handshake,color: 
                            Color(0xff41ab7f),size: 23),)
                            //child: IconButton(icon: FaIcon(FontAwesomeIcons.check,color: 
                            Color(0xff41ab7f),size: 23),)

                            //)
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Positioned(
                bottom: 20,
                right: 20,
                left: 20,
                child: Container(
                  height: 60,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(16),
                    color: Color(0xFF0A0E21),
                  ),
                  width: MediaQuery.of(context).size.width,
                ),
              ),
              Positioned(
                bottom: 20,
                right: 20,
                left: 20,
                child: Container(
                  height: 60,
                  width: 150,
                  child: FlatButton(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16),
                    ),
                    //color: Color(0xff41ab7f).withOpacity(0.2),
                    textColor: Color(0xff41ab7f),
                    padding: EdgeInsets.all(8.0),
                    splashColor: Color(0xff41ab7f).withOpacity(0.2),
                    onPressed: () async {
                      await setData();
                      if (jsonDecode(_accepted)['Status'] == '1') {
                        print("_userId : " + _userId);
                        print("_accepted : " + _accepted);
                        print("orderID : " + widget.orderID);

                        Navigator.push(context,
                            FadeRoute(page: SplashScreenOrderAccepted()));
                      }
                    },
                    child: Text(
                      'Accepter la commande',
                      style: TextStyle(fontSize: 15.0),
                    ),
                  ),
                ),
              ),
            ],
          );
        } else if (snapshot.hasError) {
          return Text("${snapshot.error}");
        }

        // By default, show a loading spinner.
        return Center(child: CircularProgressIndicator());
      },
       ),
      ),
     );
     }
     }

     class SplashScreenOrderAccepted extends StatefulWidget {
         final String orderID;

     const SplashScreenOrderAccepted({Key key, this.orderID}) : super(key: key);

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

     class _SplashScreenOrderDeliveredState
       extends State<SplashScreenOrderAccepted> {
        @override
      void initState() {
      super.initState();
        Timer(Duration(seconds: 1),
      () => Navigator.push(context, FadeRoute(page: OrderListScreen())));
         }

          @override
          Widget build(BuildContext context) {
          return Scaffold(
             backgroundColor: Color(0xFF101427),
            body: Container(
            margin: EdgeInsets.all(35),
           child: Container(
           height: (MediaQuery.of(context).size.height),
           width: (MediaQuery.of(context).size.width),
            child: Center(
          child: FaIcon(
        FontAwesomeIcons.solidHeart,
        size: 90,
        color: Colors.redAccent,
              )),
              ),
             ),
          );
        }
           }
flutter
dart
asked on Stack Overflow Sep 25, 2020 by oussama ayadi • edited Sep 25, 2020 by Anurag Tripathi

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0