简体   繁体   中英

Listview force scrolling to the top in flutter

Listview Code

    return FutureBuilder<bool>(
      future: getData(),
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        if (!snapshot.hasData) {
          return SizedBox();
        } else {
          return Container(
            margin: PHONE ? EdgeInsets.only(top:AppBar().preferredSize.height + MediaQuery.of(context).padding.top + 90, bottom: 90)
            : EdgeInsets.only(top:AppBar().preferredSize.height + MediaQuery.of(context).padding.top + 140, bottom: 100),
            child: ListView.builder(
              physics: BouncingScrollPhysics(),
              itemCount: data.length,
              addAutomaticKeepAlives: true,
              scrollDirection: Axis.vertical,
              itemBuilder: (BuildContext context, int index) {
                widget.animationController.forward();
                return AnimatedBuilder(
                  animation: widget.animationController,
                  builder: (BuildContext context, Widget child) {
                    return ProgramsTitleView(
                      animation: Tween<double>(begin: 0.0, end: 1.0).animate(
                        CurvedAnimation(
                          parent: widget.animationController,
                          curve: Interval((1 / data.length) * index, 1.0,
                              curve: Curves.fastOutSlowIn),
                        ),
                      ),
                      animationController: widget.animationController,
                      titleText: data[index]['Heading'],
                      type: widget.screen,
                    );
                  },
                );
              },
            ),
          );
        }
      },
    );

I have a listview which whose data is populated from http request. The weird thing about this is that it loads the data properly and scrolls down properly but if i scroll up a little bit, it force scrolls to the top no matter how far down i have scrolled before. I looked everywhere but didn't find anybody with the same issue. Am i missing somethings which is causing this error?

In this case, I think it's better to use StreamBuilder instead of FutureBuilder since it only rebuilds the screen when there's change in data. So in your getData() function, you can add the data to Stream instead.

final controller = StreamController();

getData() async {
  final data = await _someCallToApi();
  controller.add(data);
}

Then listen to it in the UI:

 return StreamBuilder(
      stream: controller.stream,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        if (!snapshot.hasData) {
          return SizedBox();
 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM