Home > Blockchain >  Refresh first screen after close second in Flutter
Refresh first screen after close second in Flutter

Time:11-19

I have a few screens

In my app navigation with routes

routes: {
        '/main': (context) => const HomeView(),
        '/auth_client': (context) => const AuthClientView(),
        '/auth_company': (context) => const AuthCompanyView(),
        '/reg_company': (context) => const RegCompanyView(),
        '/client': (context) => const ClientView(),
        '/company': (context) => const CompanyView(),
        '/company_profile': (context) => const CompanyProfileView(),
        '/company_add_marker': (context) => const CompanyAddMarkerView(),
},

also i use bottomNavigationBar and "CompanyProfileView" screen work with selectTab.


import 'package:flutter/material.dart';

import './company_qr_view.dart';
import './company_visits_view.dart';
import './company_profile_view.dart';

class CompanyView extends StatelessWidget {
  const CompanyView({super.key});

  @override
  Widget build(BuildContext context) {
    return const CompanyBodyView();
  }
}

class CompanyBodyView extends StatefulWidget {
  const CompanyBodyView({super.key});

  @override
  State<CompanyBodyView> createState() => _CompanyBodyViewState();
}

class _CompanyBodyViewState extends State<CompanyBodyView> {
  int _selectedTab = 0;

  static const List<Widget> _widgetOptions = <Widget>[
    CompanyQRView(),
    CompanyVisitsView(),
    CompanyProfileView(),
  ];

  void onSelectTab(int index) {
    if (_selectedTab == index) return;
    setState(() {
      _selectedTab = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: _widgetOptions[_selectedTab],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedTab,
        fixedColor: Colors.lime,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.discount),
            label: 'QR',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.list),
            label: 'Visits',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.edit),
            label: 'Profile',
          ),
        ],
        onTap: onSelectTab,
      ),
    );
  }
}


I have a question when working with two screens CompanyProfileView() and CompanyAddMarkerView()

First screen "company_profile"

When it start i check status in Firebase, use initstate where do a function and define bool

I have a block "Marker on map" on this first screen. It's changeable.

Text "Add location" and grey icon - if bool true (status from Firebase - hide)

Text "Location added" and lime icon - if bool false (status from Firebase - active)

Block "Marker on map"


import 'package:flutter/material.dart';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';



class CompanyProfileBodyMarkerView extends StatefulWidget {
  const CompanyProfileBodyMarkerView({super.key});

  @override
  State<CompanyProfileBodyMarkerView> createState() =>
      _CompanyProfileBodyMarkerViewState();
}

class _CompanyProfileBodyMarkerViewState
    extends State<CompanyProfileBodyMarkerView> {
  bool _hiddenMarker = true;

  @override
  void initState() {
    checkStatusMarker();
    super.initState();
  }

  Future<void> checkStatusMarker() async {
    var document = FirebaseFirestore.instance
        .collection('companies')
        .doc(FirebaseAuth.instance.currentUser!.uid);

    var snapshot = await document.get();
    Map<String, dynamic>? data = snapshot.data();
    var markerStatus = data!['map_marker'];

    if (markerStatus == 'active') {
      setState(() {
        _hiddenMarker = false;
      });
    }
    return;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.fromLTRB(10, 15, 10, 15),
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: const [
              Text(
                'Marker on map',
                style: TextStyle(
                  fontSize: 15,
                  color: Colors.grey,
                ),
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              _hiddenMarker
                  ? Row(
                      children: [
                        const Text(
                          'Add location',
                          style: TextStyle(fontSize: 16),
                        ),
                        IconButton(
                          onPressed: () {
                            Navigator.of(context)
                                .pushNamed('/company_add_marker');
                          },
                          icon: const Icon(
                            Icons.location_on_sharp,
                            color: Colors.grey,
                            size: 32,
                          ),
                        ),
                      ],
                    )
                  : Row(
                      children: [
                        const Text(
                          'Location added',
                          style: TextStyle(fontSize: 16),
                        ),
                        IconButton(
                          onPressed: () {
                            Navigator.of(context)
                                .pushNamed('/company_add_marker');
                          },
                          icon: const Icon(
                            Icons.location_on_sharp,
                            color: Colors.lime,
                            size: 32,
                          ),
                        ),
                      ],
                    ),
            ],
          ),
          const SizedBox(
            height: 10,
          ),
        ],
      ),
    );
  }
}

Second screen "company_add_marker"


import 'dart:async';

import 'package:flutter/material.dart';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:geolocator/geolocator.dart';

import 'package:google_maps_flutter/google_maps_flutter.dart';

class CompanyAddMarkerView extends StatelessWidget {
  const CompanyAddMarkerView({super.key});

  @override
  Widget build(BuildContext context) {
    return const CompanyAddMarkerBodyView();
  }
}

class CompanyAddMarkerBodyView extends StatefulWidget {
  const CompanyAddMarkerBodyView({super.key});

  @override
  State<CompanyAddMarkerBodyView> createState() =>
      _CompanyAddMarkerBodyViewState();
}

class _CompanyAddMarkerBodyViewState extends State<CompanyAddMarkerBodyView> {
  @override
  void initState() {
    _getLocation();
    super.initState();
  }

  LatLng? _centerPosition;

  late GoogleMapController mapController;

  Completer<GoogleMapController> _controller = Completer();

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  LatLng? _currentPosition;
  bool _isLoading = true;

  _getLocation() async {
    LocationPermission permission;
    permission = await Geolocator.requestPermission();

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    double lat = position.latitude;
    double long = position.longitude;

    LatLng location = LatLng(lat, long);

    setState(() {
      _currentPosition = location;
      _isLoading = false;
    });
    print(_currentPosition);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Location'),
      ),
      body: Container(
        child: Stack(
          children: [
            _isLoading
                ? const Center(
                    child: CircularProgressIndicator(
                      color: Colors.lime,
                    ),
                  )
                : GoogleMap(
                    mapType: MapType.normal,
                    onMapCreated: _onMapCreated,
                    initialCameraPosition: CameraPosition(
                      target: _currentPosition!,
                      zoom: 17.0,
                    ),
                    myLocationEnabled: true,
                    onCameraMove: (CameraPosition cp) {
                      LatLng center = cp.target;
                      _centerPosition = center;
                    },
                  ),
            const Center(
              child: Icon(
                Icons.location_on_sharp,
                color: Colors.lime,
                size: 46,
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 20),
              child: Positioned.fill(
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: ElevatedButton(
                    onPressed: addMarker,
                    child: const Text('Add'),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  void addMarker() async {
    var _markerData = _centerPosition.toString();

    if (_markerData == 'null') {
      return;
    }
    final FirebaseAuth _auth = await FirebaseAuth.instance;
    final FirebaseFirestore _firestore = await FirebaseFirestore.instance;

    var getCoor = _markerData.split('(')[1].trim();
    var finalCoor = getCoor.substring(0, getCoor.length - 1).trim();
    var firstcoord = finalCoor.substring(0, finalCoor.indexOf(','));
    var secondcoord = finalCoor.substring(finalCoor.indexOf(',')   1).trim();

    await _firestore
        .collection('companies')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .update(
      {
        'coordinates_lat': firstcoord,
        'coordinates_long': secondcoord,
        'map_marker': 'active',
      },
    );
    Navigator.pop(context);
  }
}

I clicked on the icon and second screen is opened

There i can to set marker, if marker is install i need to close screen and go to first screen.

And i have a problem, screen is closed but initState is NOT call and value "bool" remains the same.

After close second screen Navigator.pop(context); screen is not updating

The user sees a gray icon and the text "add location", even though user set the marker. It`s wrong.

If i go to another screen and reopened screen "company_profile" initState is called and it will be works fine.

But how i can call refresh screen after pressing the button "Add" on the screen "company_add_marker" ?

I try to find solution, and found this:

Use this in 1st page:

Navigator.pushNamed(context,'/page2').then((_) => setState(() {})); 

and this in 2nd page:

Navigator.pop(context); 

Change with my data

Navigator.pushNamed(context,'/company_add_marker').then((_) => setState(() {})); 

It`s not working in my code. Again text "Add location" and grey icon

CodePudding user response:

can you try this?

Navigator.pushNamed(context,'/company_add_marker').then((_) => checkStatusMarker());

maybe it`s not working in your code because your code just call setState, not re read updated data

  • Related