【问题标题】:flutter PageView onPageChanged with setstate用 setstate 扑动 PageView onPageChanged
【发布时间】:2021-10-13 23:40:05
【问题描述】:

我正在使用 PageView 但如果我滑动更改它会更改页面但是如果我将 onPageChanged 设置为 setState 以便我访问当前索引它不会更改页面。

这是我的代码

int _indicatorsPages = 0;
最终的 PageController 控制器 = PageController(initialPage: 0);

更改(int page){ 设置状态((){ _indicatorsPages = 页; }); }

构建代码

Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          leading: Row(
            children: [
              SizedBox(
                width: 10,
              ),
              GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => SettingsFMC(),
                    ),
                  );
                },
                child: Container(
                  height: 40,
                  width: 40,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.5),
                        spreadRadius: 1, blurRadius: 2,
                        offset: Offset(0, 3), // i change position of shadow
                      ),
                    ],
                  ),
                  child: Center(
                      child: Icon(
                    FontAwesomeIcons.slidersH,
                    size: 20,
                    color: Colors.black,
                  )),
                ),
              ),
            ],
          ),
          elevation: 0,
          backgroundColor: Colors.transparent,
          actions: [
            GestureDetector(
              onTap: () async {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => Actitvities(),
                  ),
                );
                final doc = await firestore
                    .collection('feeds')
                    .doc(auth.currentUser.uid)
                    .collection('feedsItems')
                    .get();
                if (doc.docs.isNotEmpty) {
                  firestore
                      .collection('feeds')
                      .doc(auth.currentUser.uid)
                      .collection('feedsItems')
                      .get()
                      .then((value) {
                    value.docs.forEach((doc) {
                      doc.reference.update({'seen': true});
                    });
                  });
                }
              },
              child: Container(
                height: 40,
                width: 40,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.5),
                      spreadRadius: 1, blurRadius: 2,
                      offset: Offset(0, 3), // i change position of shadow
                    ),
                  ],
                ),
                child: StreamBuilder(
                    stream: firestore
                        .collection('feeds')
                        .doc(auth.currentUser.uid)
                        .collection('feedsItems')
                        .where('seen', isEqualTo: false)
                        .snapshots(),
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return Center(
                            child: Icon(
                          Icons.notifications_none_outlined,
                          size: 20,
                          color: Colors.black,
                        ));
                      }
                      if (snapshot.data.docs.isEmpty) {
                        return Center(
                            child: Icon(
                          Icons.notifications_none_outlined,
                          size: 20,
                          color: Colors.black,
                        ));
                      }
                      return Badge(
                        animationType: BadgeAnimationType.scale,
                        badgeContent: Text('${snapshot.data.docs.length}'),
                        position: BadgePosition.topStart(),
                        showBadge: true,
                        child: Center(
                            child: Icon(
                          Icons.notifications_none_outlined,
                          size: 20,
                          color: Colors.black,
                        )),
                      );
                    }),
              ),
            ),
            SizedBox(
              width: 10,
            ),
          ],
        ),
        extendBodyBehindAppBar: true,
        body: userProfileLoading
            ? Center(
                child: CircularProgressIndicator(),
              )
            : Stack(
                children: [
                  Container(
                    height: MediaQuery.of(context).size.height / 1.6,
                    child: StreamBuilder(
                        stream: firestore
                            .collection('Image')
                            .doc(widget.viewId)
                            .collection('Photos')
                            .orderBy('timestap', descending: false)
                            .snapshots(),
                        builder: (context, AsyncSnapshot snapshot) {
                          int idx = 0;
                          List<Widget> list = [];
                          if (snapshot.connectionState ==
                              ConnectionState.waiting) {
                            return Center(
                              child: CircularProgressIndicator(),
                            );
                          }
                          if (!snapshot.hasData) {
                            return Center(
                              child: Text("No image Found, Add images"),
                            );
                          } else {
                            if (snapshot.hasError) {
                              return Center(child: Text("fetch error"));
                            } else {
                              for (int i = 0;
                                  i < snapshot.data.docs.length;
                                  i++) {
                                //  print('the lent of the document is $idx');
                                list.add(
                                  FullScreenWidget(
                                    child: Hero(
                                      tag: "customTag",
                                      child: Image.network(
                                        snapshot.data.docs[idx]
                                            .data()['picture'],
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                  ),
                                );
                                idx++;
                              }
                              return Stack(
                                children: [
                                  PageView(
                                    key: _key,
                                    scrollDirection: Axis.horizontal,
                                    controller: controller,
                                    onPageChanged: change,
                                    // onImageChange: (pre, current) {
                                    //   print('this current : $current');
                                    //   setState(() {
                                    //     indicatorsPages = current;
                                    //   });
                                    // },
                                    // boxFit: BoxFit.cover,
                                    // autoplay: false,
                                    // animationCurve: Curves.fastOutSlowIn,
                                    // animationDuration:
                                    //     Duration(milliseconds: 1000),

                                    // dotIncreasedColor: Colors.orange,
                                    // dotBgColor: Colors.transparent,
                                    // dotPosition: DotPosition.bottomCenter,
                                    // dotVerticalPadding:
                                    //     MediaQuery.of(context).size.height / 15,
                                    //showIndicator: false,
                                    // indicatorBgPadding: 7.0,
                                    children: list,
                                  ),
                                  Positioned(
                                    right:
                                        MediaQuery.of(context).size.width / 2,
                                    bottom: 75,
                                    child: Container(
                                        decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(20),
                                            color: Colors.white),
                                        child: indicat.DotsIndicator(
                                          dotsCount: list.length,
                                          position: _indicatorsPages.toDouble(),
                                          decorator: DotsDecorator(
                                            color:
                                                Colors.grey, // Inactive color
                                            activeColor: Colors.black,
                                          ),
                                        )),
                                  )
                                ],
                              );
                            }
                          }
                        }),
                  ),

【问题讨论】:

  • onPageChanged 将在您更改页面时被调用。在onPageChanged 中添加一个简单的打印语句并通过滑动更改页面将打印它。不是为了换页
  • 我已经做到了。问题没有改变。它只会达到 1
  • I/flutter (17367):这是页面 1 D/ViewRootImpl@eeb29ee[MainActivity](17367):ViewPostIme 指针 0 D/ViewRootImpl@eeb29ee[MainActivity](17367):ViewPostIme 指针 1 I/flutter (17367): 这是页面 1 D/ViewRootImpl@eeb29ee[MainActivity](17367): ViewPostIme 指针 0 D/ViewRootImpl@eeb29ee[MainActivity](17367): ViewPostIme 指针 1 I/flutter (17367): this是第 1 页
  • @Pokaboom 问题是,如果我删除 setstate 它将起作用但不适用于 setstate..

标签: flutter dart flutter-layout


【解决方案1】:

你错了。当你使用 pageView 时,它会在页面改变后调用 onPageChnaged 函数。如果你想以编程方式改变页面,你应该使用 pageView.animateToPage() 函数。

【讨论】:

  • 我想滑动切换页面。更新当前索引的指示....如果您可以提供示例代码。 setstate 导致了问题,因为如果我删除 setstate 它会更改页面但指示器没有更新
  • 让我知道你的Skype或anydesk。我会指导你。我的 Skype id 是 live.oniangel129
  • 477 029 748 anydesk
  • 你不允许你的anydesk截图权限
  • 给我一秒钟
【解决方案2】:
import 'package:flutter/material.dart';

class OnBoarding extends StatefulWidget {
  @override
  _OnBoardingState createState() => _OnBoardingState();
}

class _OnBoardingState extends State<OnBoarding> {
  PageController controller;
  int currentIndex = 0;

  @override
  void initState() {
    controller = PageController();
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueAccent[200],
      body: Stack(
        children: [
          PageView(
            onPageChanged: onchahged,
            controller: controller,
            children: [
              Container(
                child: Image.asset('assets/fierceninja.png'),
              ),
              Container(
                child: Image.asset('assets/ninja.png'),
              ),
              Container(
                child: Image.asset('assets/ninjahead.jpg'),
              ),
            ],
          ),
        ],
      ),
    );
  }
  onchahged(int index) {
    setState(() {
      currentIndex = index;
    });
  }
}

这是一个完整的例子。

【讨论】:

  • 不工作...我不知道为什么不更改页面...但是如果我删除 setstate 它会改变..
猜你喜欢
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 2021-07-06
相关资源
最近更新 更多