将值从孩子传递给父母,然后重建状态

时间:2021-03-05 12:03:21

标签: flutter state

我尝试将 carouselwidget 索引的值传递给另一个小部件。但是我的第二个小部件中返回的值是空的(例如,如果我在轮播中拖动一个值,getindex 函数会打印索引值,但 background_widget 中的打印测试保持初始化为空

我认为 pb 是我试图通过共同的父级(屏幕堆叠轮播和地图一起)将变量(索引)从孩子(轮播)传递到另一个(地图)。

我现在正在尝试在提供者的帮助下传递索引,但没有成功(并且构建模型和提供者只是为了在同一级别的太子之间传递 af**ing 变量似乎真的有点矫枉过正):< /p>

import 'package:provider/provider.dart';
import 'package:algua_alpha/provider/provideIndex.dart';      

/*All the variables definition are not published here */

//// model class for index
class Index {
  final int id;
  Index(this.id);
}

class ProvideIdx with ChangeNotifier {
  Index _index;

  Index get index {
    print(_index);
    return _index;
  }

  void changeId() {
    notifyListeners();
  }
}

class RegionSelection extends StatefulWidget {
  final String region;
  RegionSelection(this.region); 
  @override
  _RegionSelectionState createState() => _RegionSelectionState(region);
}
class _RegionSelectionState extends State<RegionSelection> {

// main screen where Carousel and map are stacked 
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (ctx) => ProvideIdx(),
      child: Scaffold(
          body: Container(
              child:!isLoading?
               Stack(
                 children: <Widget>[
                      Maposm(region,// this widget need the Index of the carousel slider
                      ), 
                      Align(
                        alignment: Alignment.bottomCenter,
                        child: CarouselSlider.builder( //========= Carousel
                          itemBuilder: (BuildContext c, index) {
                            return GestureDetector(
                                onTap: () {
                                  Navigator.of(context).push(MaterialPageRoute(
                                      builder: (context) => NewScreen(
                                            objectlist: region,
                                            item: index,
                                          )));
                                   },
                                   );
                          itemCount: region.length,
                          options: CarouselOptions(
                              enableInfiniteScroll: true,
                              scrollDirection: Axis.horizontal,
                              enlargeCenterPage: true,
                              onPageChanged: (index, reason) { // this callback initialize the new index value
                                setState(() {
                                  Index(index);
                                });
                              },
                              );
                              }
                      )
                    ])
                  : Center(
                      child: CircularProgressIndicator(
                          backgroundColor: Colors.white,
                          valueColor: AlwaysStoppedAnimation<Color>(
                              Colors.orange[300]))
                        ),
    );
  }
}
//=============================== The Map ===============================
class Maposm extends StatefulWidget {
  //final carouselID;
  final region;
  Maposm(this.region); 
  @override
  _MaposmState createState() =>_MaposmState(region); 
}
class _MaposmState extends State<Maposm> {


  @override
  Widget build(BuildContext context) {
    final indexes = Provider.of<Index>(context);
    final carouselID = indexes.id; //get carousel id
    List<Marker> markers = []; 
    for (var i = 0; i < region.length; i++) {
      var m = Marker(
          point:
              LatLng(region[i].xy[0], region[i].xy[1]),
          builder: (ctx) => InkWell(
                child: (carouselID == i // index of marker builder == index of carousel
                    ? Icon(
                        Icons.assistant,
                        color: Colors.pink[700],
                        size: 20,
                      )
                    : Icon( // else
                        Icons.brightness_1_sharp,
                        color: Colors.black87,
                        size: 4,
                      )),
                onDoubleTap: null,
              ));
      markers.add(m);
    }

    return FlutterMap(
        options: MapOptions(
          interactive: true,
          slideOnBoundaries: true,
          bounds: LatLngBounds(
              LatLng(coordxy[0], coordxy[1]), LatLng(coordxy[2], coordxy[3])),
        ),
        layers: [
          TileLayerOptions(
              urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
              subdomains: ['a', 'b', 'c']),
          MarkerLayerOptions(markers: markers)
        ]);
  }
}

0 个答案:

没有答案