Fakultas Ilmu Komputer UI

dashboard.dart 20 KB
Newer Older
Yoga Pratama's avatar
Yoga Pratama committed
1
import 'package:bisaGo/bloc/cloud_messaging_bloc.dart';
2
import 'package:bisaGo/bloc/lokasi_response_bloc.dart';
3
import 'package:bisaGo/model/komentar.dart';
4
import 'package:bisaGo/model/lokasi.dart';
5
6
import 'package:bisaGo/bloc/kegiatan_terdekat_bloc.dart';
import 'package:bisaGo/model/kegiatan.dart';
7
8
import 'package:bisaGo/page/filter_fasilitas/postingan/detail_post_kegiatan.dart';
import 'package:bisaGo/repository/kegiatan_repository.dart';
9
import 'package:bisaGo/utils/custom_kegiatan_terdekat_button.dart';
10
import 'package:bisaGo/network/data/network_model.dart';
11
12
import 'package:bisaGo/page/filter_fasilitas/postingan/detail_post.dart';
import 'package:bisaGo/repository/komentar_repository.dart';
13
import 'package:bisaGo/utils/custom_dashboard_location_button.dart';
14
import 'package:bisaGo/utils/location_turn_on_dialog.dart';
15
import 'package:firebase_core/firebase_core.dart';
16
import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
17
import 'package:firebase_messaging/firebase_messaging.dart';
18
import 'package:flushbar/flushbar.dart';
19
import 'package:flutter/material.dart';
20
import 'package:flutter_dotenv/flutter_dotenv.dart';
21
import 'package:geolocator/geolocator.dart';
22
import 'package:google_maps_flutter/google_maps_flutter.dart';
23
24
25
26
import 'package:bisaGo/component/bisago_appbar.dart';
import 'package:bisaGo/component/bisago_drawer.dart';
import 'package:bisaGo/config/styles.dart';
import 'package:bisaGo/page/pencarian/pencarian.dart';
27
import 'package:google_maps_webservice/places.dart';
Yoga Pratama's avatar
Yoga Pratama committed
28
import 'package:shared_preferences/shared_preferences.dart';
Ardian Ghifari's avatar
Ardian Ghifari committed
29
import 'package:shimmer/shimmer.dart';
30

31
import '../filter_fasilitas/postingan/detail_post.dart';
32
33

class Dashboard extends StatefulWidget {
34
  const Dashboard({Key key}) : super(key: key);
35
  @override
36
37
38
39
  DashboardState createState() => DashboardState();
}

class DashboardState extends State<Dashboard> {
Fakhira Devina's avatar
Fakhira Devina committed
40
  final double cameraZoom = 15;
41
42
43
  GoogleMapController mapController;
  Geolocator geolocator;
  LatLng currentLocation;
44
  Set<Marker> markers = {};
45
  bool _enabled = true;
46

47
  LokasiResponseBloc bloc = LokasiResponseBloc();
48
  KegiatanTerdekatBloc blocKegiatanTerdekat = KegiatanTerdekatBloc();
Yoga Pratama's avatar
Yoga Pratama committed
49
  CloudMessagingBloc cloudMessagingBloc = CloudMessagingBloc();
50

51
52
53
54
  FirebaseMessaging _firebaseMessaging;

  bool _initialized = false;

55
  DateTime _lastNotification;
56

57
58
59
  @override
  void initState() {
    super.initState();
60
    _showTurnOnLocationDialog(context);
61
    geolocator = Geolocator()..forceAndroidLocationManager;
62
    initDynamicLinks();
63
    setInitialLocation();
64
65
66
67
68
69
70
71
72
73
74
75

    if (!_initialized) {
      _initialized = true;
      _setupFirebase();
    }
  }

  void _setupFirebase() async {
    await Firebase.initializeApp();
    _firebaseMessaging = FirebaseMessaging.instance;

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
76
77
78
79
80
81
82
83
      final now = DateTime.now();

      if (_lastNotification != null &&
          _lastNotification.add(Duration(seconds: 10)).isAfter(now)) return;

      _lastNotification = now;
      final data = message.data;
      final String msg = data['message'];
84
85
86
      final String title = data['title'];
      Flushbar(
        title: title,
87
        message: msg,
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
        duration: Duration(seconds: 8),
        backgroundColor: Color(0xFF003566),
        onTap: (_) {
          if (data['type'] == 'fasilitas') {
            final String placeId = data['place_id'];
            final id = int.parse(data['id']);
            _navigateToDetailFasilitasPage(context, placeId, id);
          } else if (data['type'] == 'kegiatan') {
            final String placeId = data['place_id'];
            final id = int.parse(data['id']);
            _navigateToDetailKegiatanPage(context, placeId, id);
          }
        },
        flushbarStyle: FlushbarStyle.GROUNDED,
        flushbarPosition: FlushbarPosition.TOP,
      ).show(context);
104
    });
105

106
107
108
109
110
111
112
113
114
115
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      final data = message.data;
      if (data['type'] == 'fasilitas') {
        final String placeId = data['place_id'];
        final id = int.parse(data['id']);
        _navigateToDetailFasilitasPage(context, placeId, id);
      } else if (data['type'] == 'kegiatan') {
        final String placeId = data['place_id'];
        final id = int.parse(data['id']);
        _navigateToDetailKegiatanPage(context, placeId, id);
116
117
      }
    });
118

119
120
121
122
    _requestFCMToken();
  }

  void _requestFCMToken() async {
Yoga Pratama's avatar
Yoga Pratama committed
123
124
125
126
127
128
    final fcmToken = await _firebaseMessaging.getToken();
    final sharedPreferences = await SharedPreferences.getInstance();
    final token = sharedPreferences.getString('token');
    if (token != null) {
      await cloudMessagingBloc.sendFCMToken(fcmToken, token);
    }
129
130
  }

131
  void _navigateToPencarianPage(BuildContext context) {
132
    final route = MaterialPageRoute(builder: (_) => const Pencarian());
133
134
135
    Navigator.of(context).push(route);
  }

136
137
138
139
  // void _navigateToInformasiLayananDisabilitasPage(BuildContext context) {
  //   final route = MaterialPageRoute(builder: (_) => ListSekolah());
  //   Navigator.of(context).push(route);
  // }
140

141
  static const textFieldKey = Key('Text Field Mau Kemana');
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167

  void _showTurnOnLocationDialog(BuildContext context) {
    bloc.isLocationServiceTurnedOn().then(
      (value) {
        if (!value) {
          showDialog(
            context: context,
            builder: (BuildContext context) {
              return LocationTurnOnDialog(
                message: 'Mohon Menyalakan Lokasi',
                title: 'Lokasi',
                onPressed: () {
                  bloc.requestLocationService().then((loc) {
                    if (loc) {
                      Navigator.pop(context);
                    }
                  });
                },
              );
            },
          );
        }
      },
    );
  }

168
169
170
  @override
  Widget build(BuildContext context) {
    return Scaffold(
171
      drawer: BisaGoDrawer(),
172
173
      body: Stack(
        key: const Key('Stack'),
174
        //alignment: AlignmentDirectional.bottomStart,
175
176
        children: <Widget>[
          Container(
177
              padding: EdgeInsets.only(top: 35),
Yoga Pratama's avatar
Yoga Pratama committed
178
179
180
181
              child: _buildGoogleMap(context)),
          Column(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <
              Widget>[
            Container(
182
183
184
185
186
                height: 40,
                alignment: Alignment.center,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
Yoga Pratama's avatar
Yoga Pratama committed
187
188
                      bottomLeft: Radius.circular(10.0),
                      bottomRight: Radius.circular(10.0)),
189
190
                ),
                child: Padding(
Yoga Pratama's avatar
Yoga Pratama committed
191
192
193
194
                    padding:
                        const EdgeInsets.symmetric(horizontal: doubleSpace),
                    child: StreamBuilder<NetworkModel>(
                        stream: blocKegiatanTerdekat.kegiatanTerdekatStream,
195
196
197
198
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            switch (snapshot.data.status) {
                              case Status.loading:
199
                                _enabled = true;
200
                                return Container(
201
                                    child: _buildMockKegiatanTerdekatWidget());
202
203
                                break;
                              case Status.completed:
204
                                _enabled = false;
Yoga Pratama's avatar
Yoga Pratama committed
205
206
207
                                final kegiatanTerdekat = snapshot.data.data;
                                return _buildKegiatanTerdekatWidget(
                                    kegiatanTerdekat);
208
209
                                break;
                              case Status.error:
210
                                _enabled = false;
211
                                return Container(
Yoga Pratama's avatar
Yoga Pratama committed
212
213
214
215
216
217
218
219
220
                                    child: const Center(
                                  child: Text(
                                      'Tidak ada kegiatan dalam waktu dekat',
                                      style: TextStyle(
                                        color: greenPrimary,
                                        fontSize: 16,
                                        fontFamily: 'Muli',
                                      )),
                                ));
221
222
223
224
225
                                break;
                            }
                            return Container();
                          }
                          return Container();
Yoga Pratama's avatar
Yoga Pratama committed
226
227
228
229
230
231
232
233
                        }))), // Container info kegiatan
            Container(
              height: 285,
              alignment: Alignment.bottomCenter,
              decoration: const BoxDecoration(
                color: white,
                borderRadius: BorderRadius.all(
                  Radius.circular(10.0),
234
                ),
Yoga Pratama's avatar
Yoga Pratama committed
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
              ),
              padding: const EdgeInsets.symmetric(
                  horizontal: doubleSpace, vertical: doubleSpace),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  InkWell(
                    key: const Key('Navigate to Pencarian'),
                    onTap: () => _navigateToPencarianPage(context),
                    child: Container(
                      key: const Key('Container Text Field'),
                      padding: EdgeInsets.zero,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: regularBorderRadius,
                          border: Border.all(color: greenPrimary),
                          boxShadow: regularShadow),
                      child: TextFormField(
                        enabled: false,
                        key: const Key('Text Field Mau Kemana'),
                        decoration: const InputDecoration(
                          prefixIcon: Icon(
                            Icons.search,
                            color: greenPrimary,
                            size: 25,
                          ),
                          border: InputBorder.none,
                          fillColor: Colors.white,
                          labelText: 'Tekan untuk mencari tempat',
                          labelStyle: TextStyle(
                              color: greenPrimary,
                              fontSize: 20,
                              fontFamily: 'Muli',
                              fontWeight: FontWeight.w700),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: doubleSpace),
                  const Text(
                    'Paling sering dicari',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 10),
                  StreamBuilder<NetworkModel<LokasiListResponse>>(
                      stream: bloc.lokasiListStream,
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          switch (snapshot.data.status) {
                            case Status.loading:
290
                              _enabled = true;
Yoga Pratama's avatar
Yoga Pratama committed
291
                              return Container(
292
                                  height: 130, child: _buildMockLokasiWidget());
Yoga Pratama's avatar
Yoga Pratama committed
293
294
                              break;
                            case Status.completed:
295
                              _enabled = false;
Yoga Pratama's avatar
Yoga Pratama committed
296
297
298
299
                              final places = snapshot.data.data.listLokasi;
                              return _buildLokasiWidget(places);
                              break;
                            case Status.error:
300
                              _enabled = false;
Yoga Pratama's avatar
Yoga Pratama committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
                              return Container(
                                height: 130,
                                child: const Center(
                                  child: Text('Gagal untuk mendapatkan tempat'),
                                ),
                              );
                              break;
                          }
                          return Container();
                        }
                        return Container();
                      }),
                ],
              ),
            ),
          ])
317
        ],
318
      ),
319
320
321
322
323
324
325
326
327
328
      // floatingActionButton: FloatingActionButton.extended(
      //   key: const Key('FloatingActionButton'),
      //   onPressed: () {
      //     _navigateToInformasiLayananDisabilitasPage(context);
      //   },
      //   label: Text('Informasi Layanan Disabilitas'),
      //   icon: Icon(Icons.search),
      //   backgroundColor: greenPrimary,
      // ),
      // floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
329
330
331
      appBar: const PreferredSize(
        preferredSize: Size.fromHeight(55),
        key: Key('Scaffold Text Field'),
332
        child: BisaGoAppBar(),
Agnes Handoko's avatar
Agnes Handoko committed
333
      ),
334
335
336
    );
  }

337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
  Widget _buildLokasiWidget(List<Lokasi> lokasilistresponse) {
    return Container(
      height: 130,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          Row(
              children: lokasilistresponse
                  .map<Widget>((k) => LocationIconButton(
                        location: k,
                      ))
                  .toList()),
        ],
      ),
    );
  }

354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
  Widget _buildMockLokasiWidget() {
    final mockLokasi = [
      Lokasi.fromJson({
        'name': 'Margo City',
        'alamat':
            'Jl. Margonda Raya No.358, Kemiri Muka, Kecamatan Beji, Kota Depok, Jawa Barat 16423',
        'image': 'static/img/2669211407.jpg',
        'no_telp': '02178870888',
        'counter': 69,
      }),
      Lokasi.fromJson({
        'name': 'Margo City',
        'alamat':
            'Jl. Margonda Raya No.358, Kemiri Muka, Kecamatan Beji, Kota Depok, Jawa Barat 16423',
        'image': 'static/img/2669211407.jpg',
        'no_telp': '02178870888',
        'counter': 69,
      }),
      Lokasi.fromJson({
        'name': 'Margo City',
        'alamat':
            'Jl. Margonda Raya No.358, Kemiri Muka, Kecamatan Beji, Kota Depok, Jawa Barat 16423',
        'image': 'static/img/2669211407.jpg',
        'no_telp': '02178870888',
        'counter': 69,
      }),
    ];
    return Container(
      key: Key('Shimmer loading'),
      height: 130,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          Row(
              children: mockLokasi
                  .map<Widget>((k) => Shimmer.fromColors(
                      baseColor: Colors.grey[300],
                      highlightColor: Colors.grey[100],
                      enabled: _enabled,
                      child: LocationIconButton(
                        location: k,
                      )))
                  .toList()),
        ],
      ),
    );
  }

402
  Widget _buildKegiatanTerdekatWidget(KegiatanModel kegiatanModel) {
Yoga Pratama's avatar
Yoga Pratama committed
403
    return Container(child: KegiatanTerdekatButton(kegiatan: kegiatanModel));
404
405
  }

406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
  Widget _buildMockKegiatanTerdekatWidget() {
    final mockKegiatan = KegiatanModel.fromJson({
      'id': 1,
      'place_id': 'asdfghjkl',
      'creator': 'Jovi',
      'nama_kegiatan': 'Jalan Sehat',
      'penyelenggara': 'Gubernur',
      'narahubung': 'Rafif (0880123456123456)',
      'deskripsi': 'Jalan sehat keliling kota',
      'time_start': '2021-05-15 06:00:00',
      'time_end': '2021-05-15 10:00:00',
      'image': ['a', 'b', 'c'],
    });
    return Container(child: KegiatanTerdekatButton(kegiatan: mockKegiatan));
  }

422
  Widget _buildGoogleMap(BuildContext context) {
423
    if (currentLocation == null) {
424
      return const Center(
425
        child: CircularProgressIndicator(),
426
      );
427
428
429
430
    } else {
      return GoogleMap(
        initialCameraPosition:
            CameraPosition(target: currentLocation, zoom: cameraZoom),
431
        onMapCreated: (GoogleMapController controller) {
432
          mapController = controller;
433
        },
434
        myLocationEnabled: true,
435
        markers: markers,
436
437
438
        onCameraMove: _onCameraMove,
      );
    }
439
440
  }

441
  void _onCameraMove(CameraPosition position) {
442
    setState(() {
443
      currentLocation = position.target;
444
445
446
    });
  }

447
  void setInitialLocation() async {
448
    final position = await geolocator.getCurrentPosition(
449
450
451
452
453
        desiredAccuracy: LocationAccuracy.high);

    setState(() {
      currentLocation = LatLng(position.latitude, position.longitude);
    });
454
  }
455
456
457
458
459
460
461
462
463

  Future<String> getLokasiName(String placeId) async {
    final _places = GoogleMapsPlaces(apiKey: DotEnv().env['API_KEY']);
    var details = await _places.getDetailsByPlaceId(
      placeId,
      fields: [
        'name',
      ],
    );
464
465
    final result = details.result;
    return result == null ? 'INVALID' : result.name;
466
467
  }

468
  void _navigateToDetailFasilitasPage(
469
      BuildContext context, String placeId, int fasilitasId) async {
470
471
472
473
474
475
476
477
478
    final fetches = await Future.wait([
      KomentarRepository().fetchDetailFasilitas(placeId, fasilitasId),
      getLokasiName(placeId),
    ]);
    final KomentarModel fasilitas = fetches[0];
    final String namaLokasi = fetches[1] ?? 'INVALID';
    final lokasi = Lokasi()
      ..placeId = placeId
      ..name = namaLokasi;
479
    final fasilitasRoute = MaterialPageRoute(
480
        builder: (BuildContext context) => DetailPostPage(
481
482
483
484
485
486
487
488
489
490
491
492
493
494
              lokasi: lokasi,
              komentar: KomentarModel(
                creator: fasilitas.creator,
                dateTime: fasilitas.dateTime,
                deskripsi: fasilitas.deskripsi,
                id: fasilitas.id,
                image: fasilitas.image,
                isVerified: fasilitas.isVerified,
                namaLokasi: lokasi.name,
                tag: fasilitas.tag,
                disabilitas: fasilitas.disabilitas,
                jumlah: fasilitas.jumlah,
              ),
            ));
495
    await Navigator.of(context).push(fasilitasRoute);
496
  }
497

498
499
500
501
502
503
504
505
506
507
508
509
510
  void _navigateToDetailKegiatanPage(
      BuildContext context, String placeId, int fasilitasId) async {
    final fetches = await Future.wait([
      KegiatanRepository().fetchDetailKegiatan(placeId, fasilitasId),
      getLokasiName(placeId),
    ]);
    final KegiatanModel kegiatan = fetches[0];
    final String namaLokasi = fetches[1] ?? 'INVALID';
    final lokasi = Lokasi()
      ..placeId = placeId
      ..name = namaLokasi;
    final fasilitasRoute = MaterialPageRoute(
        builder: (BuildContext context) => DetailPostKegiatanPage(
Ardian Ghifari's avatar
Ardian Ghifari committed
511
512
513
514
515
516
517
518
              lokasi: lokasi,
              kegiatan: KegiatanModel(
                id: kegiatan.id,
                placeId: lokasi.placeId,
                creator: kegiatan.creator,
                namaKegiatan: kegiatan.namaKegiatan,
                penyelenggara: kegiatan.penyelenggara,
                deskripsi: kegiatan.deskripsi,
Ardian Ghifari's avatar
Ardian Ghifari committed
519
520
521
                namaKontak: kegiatan.namaKontak,
                nomorKontak: kegiatan.nomorKontak,
                links: kegiatan.links,
Ardian Ghifari's avatar
Ardian Ghifari committed
522
523
                timeStart: kegiatan.timeStart,
                timeEnd: kegiatan.timeEnd,
Ardian Ghifari's avatar
Ardian Ghifari committed
524
525
                zonaWaktu: kegiatan.zonaWaktu,
                images: kegiatan.images,
Ardian Ghifari's avatar
Ardian Ghifari committed
526
527
              ),
            ));
528
529
530
    await Navigator.of(context).push(fasilitasRoute);
  }

531
532
  void initDynamicLinks() async {
    final data = await FirebaseDynamicLinks.instance.getInitialLink();
533

534
535
536
    _handleDeepLink(data);
    FirebaseDynamicLinks.instance.onLink(
        onSuccess: (PendingDynamicLinkData dynamicLink) async {
537
538
539
      _handleDeepLink(dynamicLink);
    }, onError: (OnLinkErrorException e) async {
      print('Link Failed: ${e.message}');
540
541
    });
  }
542
543
544
545
546
547
548

  void _handleDeepLink(PendingDynamicLinkData data) async {
    final deepLink = data?.link;
    if (deepLink != null) {
      final params = deepLink.queryParameters;
      final path = deepLink.pathSegments;
      final placeId = params['place_id'];
549
      final id = int.parse(params['id']);
550
551
552
553
554
      final type = params['type'];
      if (path[0] == 'link') {
        if (type == 'fasilitas') {
          _navigateToDetailFasilitasPage(context, placeId, id);
        } else if (type == 'kegiatan') {
555
          _navigateToDetailKegiatanPage(context, placeId, id);
556
        }
557
558
559
      }
    }
  }
560
}