在 Flutter 中打开 showmodalbottomsheet 后,屏幕上没有显示一个变量

A variable not displayed on the screen after opening showmodalbottomsheet in Flutter

提问人:Ahmed Loutfy 提问时间:11/7/2023 更新时间:11/7/2023 访问量:28

问:

我仍在学习 Flutter,并且尝试在打开 showmodalbottomsheet 后在屏幕上显示一个变量“deliveryLocation2”,该变量带来当前位置,但它仍然停留在默认值“检测位置...”。在执行热重载之前,它才会出现在屏幕上。

我希望它在显示“检测位置...”一段时间后出现在屏幕上价值

此外,我希望“circularProgressIndicator”与“检测位置...”一起仍然显示在屏幕上。值并在显示当前位置后随之消失

请注意,我为附加变量 deliveryLocation2 分配了相同的值,因为我想在打开 showmodalbottomsheet 后再次搜索该位置,而不仅仅是在 initState 方法上。

代码如下:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:talabato/constants.dart';
import 'package:talabato/screens/food_details.dart';
import 'package:talabato/screens/home/components/delivery_location.dart';

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String? deliveryLocation1, deliveryLocation2 ;
  
  @override
  void initState() {

deliveryLocation1 = deliveryLocation2 = 'Detecting Location...';

    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    detectCurrentLocation();
  }

  Widget displayCurrentLocation(
      BuildContext context, AsyncSnapshot<String> snapshot) {
    return RichText(
      overflow: TextOverflow.ellipsis,
      text: const TextSpan(
        children: [
          TextSpan(
            text: 'Delivering to\n',
            style: TextStyle(color: Colors.black),
          ),
        ],
      ),
    );
  }

  Future<Position> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    return await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
  }

  Future<String> _getAddressFromLocation(Position position) async {
    try {
      List<Placemark> placeMarks = await placemarkFromCoordinates(
        localeIdentifier: 'egy',
        position.latitude,
        position.longitude,
      );

      if (placeMarks.isNotEmpty) {
        Placemark placeMark = placeMarks.first;
        return placeMark.locality ?? "Unknown Location";
      } else {
        return "Unknown Location";
      }
    } catch (e) {
      // Handle errors
      if (kDebugMode) {
        print("Error getting address: $e");
      }
      return "Unknown Location";
    }
  }

  Future<String> detectCurrentLocation() async {
    try {
      await Future.delayed(

        const Duration(seconds: 3),
      );
      Position position = await _determinePosition();
      String location = await _getAddressFromLocation(position);

      setState(() {
        deliveryLocation1 = location;
        deliveryLocation2 = location;
      });

      return location;
    } catch (e) {
      // Handle errors
      if (kDebugMode) {
        print("Error detecting location: $e");
      }
      setState(() {
        deliveryLocation1 = "Unknown Location";
        deliveryLocation2 = "Unknown Location";
      });
      return "Unknown Location";
    }
  }

  Future loadingIndicator(BuildContext context) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return Center(
          child: Container(
            width: 100,
            height: 100,
            decoration: BoxDecoration(
              shape: BoxShape.rectangle,
              color: Colors.black.withOpacity(0.4),
              borderRadius: BorderRadius.circular(15),
            ),
            child: Center(
              child: SizedBox(
                width: 55,
                height: 55,
                child: circularProgressIndicator(6),
              ),
            ),
          ),
        );
      },
    );
  }

  Future<dynamic> chooseDeliveryLocation() {

  

    return showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (context) {
          Size size = MediaQuery.of(context).size;

          return Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(15),
              color: Colors.white,
            ),
            height: size.height * 0.45,
            width: size.width,
            padding: const EdgeInsets.all(10),
            child: Padding(
              padding: const EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    'Choose delivery location',
                    style: TextStyle(
                      fontSize: 25,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const DeliveryLocation(
                    icon: Icons.location_on_outlined,
                    locationDetails:
                        'MVVM stands for Model-View-ViewModel. The basic idea is to create.',
                    locationName: 'Home',
                  ),
                 locationDetection(
                        child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                loadingIndicator(context);
                                // Navigator.pop(context);
                              },
                              child: DeliveryLocation(
                                icon: Icons.my_location,
                                locationName: 'Deliver to current location',
                                locationDetails: deliveryLocation2!,
                                child: SizedBox(
                                  height: 25,
                                  width: 25,
                                  child: circularProgressIndicator(3),
                                ),
                              ),
                            ),
                        
                      ),
                
                  const DeliveryLocation(
                    icon: Icons.pin_drop_outlined,
                    locationDetails:
                        'MVVM stands for Model-View-ViewModel. The basic idea is to create.',
                    locationName: 'Deliver to different location',
                  ),
                ],
              ),
            ),
          );
        });
  }

  FutureBuilder<String> locationDetection({Widget? child}) {
    return FutureBuilder<String>(
      future: detectCurrentLocation(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return child!;
        } else if (snapshot.hasError) {
          // Handle error if any
          return Text('Error: ${snapshot.error}');
        } else {
          // Display the actual location when detected
          return child!;
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: double.infinity,
              height: size.height * 0.35,
              color: const Color(0xFFFFCDB2),
              child: SafeArea(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextButton(
                      onPressed: () {
   chooseDeliveryLocation();

    deliveryLocation2 = 'Detecting Location...';

                    
                      },
                      child: Text.rich(
                        TextSpan(
                          children: <InlineSpan>[
                            const TextSpan(
                              text: 'Delivering to\n',
                              style: TextStyle(color: Colors.black),
                            ),
                            WidgetSpan(
                              child: locationDetection(
                                child: Text(
                                  deliveryLocation1!,
                                  style: const TextStyle(
                                    color: Colors.black,
                                    fontSize: 20,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    IconButton(
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const FoodDetail(),
                            ),
                          );
                        },
                        icon: const Icon(Icons.coronavirus_rounded))
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

希望有人帮忙

Flutter Dart 移动开发

评论


答:

0赞 Jamaldin Sabirjanov 11/7/2023 #1

添加 Getx

String deliveryLocation1 = "".obs;
String deliveryLocation2 = "".obs;

当您使用

Obx(() => Text("$deliveryLocation1"))