无法在另一个有状态小部件类颤动中获取有状态小部件类的数据?

时间:2021-07-15 04:40:02

标签: flutter dart state

我无法将我的 MapsClass(一个 UI 屏幕)的任何数据类型导入到 AddData 类(也是一个 UI 屏幕)中。 我从 DataPush 类获取数据,这是一个简单的类。 但我想从 MapsClass 获取位置值,我正在 MapsClass 屏幕的初始状态更新该值。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
import 'AddData.dart';

class MapsClass extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MapState();
}

class _MapState extends State<MapsClass> {
  Position curLoc;                    **I want this**
  bool mapToggle = false;
  GoogleMapController mapController;
  List<Placemark> placemarks;
  double sliderVal = 0;
  String loca;
  String country;

  void initState() {
    super.initState();
    Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((curL) => {
              setState(() {
                curLoc = curL;
                mapToggle = true;
                this.getAdd();
              }),
            });
  }

  getAdd() async {
    placemarks =
        await placemarkFromCoordinates(curLoc.latitude, curLoc.longitude);
    this.country = placemarks.first.country;
    this.loca = placemarks.first.locality;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
              child: mapToggle
                  ? GoogleMap(
                      initialCameraPosition: CameraPosition(
                          target: LatLng(curLoc.latitude, curLoc.longitude),
                          zoom: 15.0),
                      myLocationEnabled: true,
                      onMapCreated: onCreate,
                      mapType: MapType.normal,
                      compassEnabled: false,
                      zoomControlsEnabled: false,
                      zoomGesturesEnabled: true,
                    )
                  : Center(
                      child: Text(
                        'Getting Location Please Wait.....',
                        style: TextStyle(fontSize: 20.0),
                      ),
                    )),
          Positioned(
            bottom: 40,
            left: 10,
            child: FloatingActionButton(
              backgroundColor: Colors.green,
              child: const Icon(Icons.create),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => AddData()),
                );
              },
            ),
          ),
          Align(
            alignment: Alignment.topCenter,
            child: SizedBox(
              width: 200.0,
              height: 120.0,
              child: Card(
                color: Colors.green,
                child: Center(
                  child: Text(
                    "You are at $loca, $country",
                    style: TextStyle(color: Colors.white),
                  ), //Text
                ), //Center
              ), //Card
            ),
          ),
          Positioned(
            bottom: 40,
            left: 70,
            child: Slider(
              activeColor: Colors.green,
              value: sliderVal,
              min: 0,
              max: 10.0,
              divisions: 2,
              label: sliderVal.round().toString(),
              onChanged: (double value) {
                setState(() {
                  sliderVal = value;
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  void onCreate(GoogleMapController controller) {
    setState(() {
      mapController = controller;
    });
  }
}

这里是我遇到错误并且无法获取位置数据类型 curLoc 的值的地方。 我无法从该类中获取任何值。

import 'package:donation_yoga/screens/maps.dart';
import 'package:donation_yoga/services/Submitform.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: AddData(),
  ));
}

class AddData extends StatefulWidget {
  @override
  _AddData createState() => _AddData();
}

class _AddData extends State<AddData> {
  final _formKey = GlobalKey<FormState>();

  final _user = DataPush();

  final ma = MapsClass();

  var position = ma.curLOC;     // THIS IS WHERE I CAN'T GET ANYTHING OR ANYWHERE in the Entire class**


  void initState() {
    super.initState();
    
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('ADD YOUR CENTER')),
        body: Container(
            padding:
                const EdgeInsets.symmetric(vertical: 16.0, horizontal: 10.0),
            child: Builder(
                builder: (context) => Form(
                    key: _formKey,
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          TextFormField(
                            decoration:
                                InputDecoration(labelText: "Enter Text"),
                            validator: (value) {
                              if (value.isEmpty) {
                                return 'Please Enter Something !!!';
                              }
                              return null;
                            },
                            onSaved: (val) =>
                                setState(() => _user.firstName = val),
                          ),
                          Container(
                            padding: const EdgeInsets.fromLTRB(0, 50, 0, 20),
                            child: Text('Options'),
                          ),
                          CheckboxListTile(
                              title: const Text('Dry'),
                              value: _user.passions[DataPush.Dry],
                              onChanged: (val) {
                                setState(
                                    () => _user.passions[DataPush.Dry] = val);
                              }),
                          CheckboxListTile(
                              title: const Text('Spot'),
                              value: _user.passions[DataPush.Spot],
                              onChanged: (val) {
                                setState(
                                    () => _user.passions[DataPush.Spot] = val);
                              }),
                          CheckboxListTile(
                              title: const Text('Red'),
                              value: _user.passions[DataPush.Red],
                              onChanged: (val) {
                                setState(
                                    () => _user.passions[DataPush.Red] = val);
                              }),
                          CheckboxListTile(
                              title: const Text('Stretch'),
                              value: _user.passions[DataPush.Strech],
                              onChanged: (val) {
                                setState(() =>
                                    _user.passions[DataPush.Strech] = val);
                              }),
                          CheckboxListTile(
                              title: const Text('Thick'),
                              value: _user.passions[DataPush.Thick],
                              onChanged: (val) {
                                setState(
                                    () => _user.passions[DataPush.Thick] = val);
                              }),
                          Container(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 16.0, horizontal: 16.0),
                              // ignore: deprecated_member_use
                              child: RaisedButton(
                                  onPressed: () {
                                    final form = _formKey.currentState;
                                    if (form.validate()) {
                                      form.save();
                                      _user.makePostRequest();
                                      _showDialog(context);
                                    }
                                  },
                                  child: Text('Save'))),
                        ])))));
  }

  _showDialog(BuildContext context) {
    Scaffold.of(context)
        // ignore: deprecated_member_use
        .showSnackBar(SnackBar(content: Text('Submitting form')));
  }
}

1 个答案:

答案 0 :(得分:0)

@artistAhmed 你没有正确传递数据。使用构造函数并传递数据,以便您可以在另一个屏幕上获取它。请参阅此 flutter 文档资源以获取专有技术。这肯定会奏效。如果您还有其他问题,请告诉我。

Send data to a new screen