在Flutter模式下下拉至REFRESH

am46iovg  于 2022-12-14  发布在  Flutter
关注(0)|答案(5)|浏览(83)

我的 Jmeter 板代码看起来像这样,这里我在getReport方法中执行get req,我已经在代码中添加了RefreshIndicator,当在容器中下拉时,它应该执行刷新,这里我调用了我的getData(),但是我没有获得刷新的内容,我在下面添加了我的代码,让我知道我是否犯了错误。
在我 Jmeter 盘下面

class Window extends StatefulWidget {
  @override
  _WindowState createState() => _WindowState();
}

class _WindowState extends State<Window> {
  Future reportList;    
  @override
  void initState() {
    super.initState();
    reportList = getReport();
  }    

  Future<void> getReport() async {
    http.Response response =
        await http.get(reportsListURL, headers: {"token": "$token"});
    switch (response.statusCode) {
      case 200: 
        String reportList = response.body;
        var collection = json.decode(reportList);
        return collection;

      case 403:
          break;

      case 401:
        return null;

      default:
        return 1;
    }
  }

  getRefreshScaffold() {
    return Center(
      child: RaisedButton(
        onPressed: () {
          setState(() {
            reportList = getReport();
          });
        },
        child: Text('Refresh, Network issues.'),
      ),
    );
  }

  getDashBody(var data) {
    double maxHeight = MediaQuery.of(context).size.height;
    return Column(
      children: <Widget>[
        Container(
          height: maxHeight - 800,
        ),
        Container(
          margin: new EdgeInsets.all(0.0),
          height: maxHeight - 188,
          child: new Center(
          child: new RefreshIndicator(          //here I am adding the RefreshIndicator
          onRefresh:getReport,                  //and calling the getReport() which hits the get api
          child: createList(context, data),
          ),),
        ),
      ],
    );
  }

  Widget createList(BuildContext context, var data) {
    Widget _listView = ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, count) {
        return createData(context, count, data);
      },
    );
    return _listView;
  }

  createData(BuildContext context, int count, var data) {
    var metrics = data["statistic_cards"].map<Widget>((cardInfo) {
      var cardColor = getColorFromHexString(cardInfo["color"]);
      if (cardInfo["progress_bar"] != null && cardInfo["progress_bar"]) {
        return buildRadialProgressBar(
          context: context,
          progressPercent: cardInfo["percentage"],
          color: cardColor,
          count: cardInfo["value"],
          title: cardInfo["title"],
        );
      } else {
        return buildSubscriberTile(context, cardInfo, cardColor);
      }
    }).toList();

    var rowMetrics = new List<Widget>();
    for (int i = 0; i < metrics.length; i += 2) {
      if (i + 2 < metrics.length)
        rowMetrics.add(Row(children: metrics.sublist(i, i + 2)));
      else
        rowMetrics.add(Row(children: [metrics[metrics.length - 1], Spacer()]));
    }
    return SingleChildScrollView(
      child: LimitedBox(
        //  maxHeight: MediaQuery.of(context).size.height / 1.30,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.center,
          children: rowMetrics,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: reportList,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
          case ConnectionState.active:
            return Center(
              child: CircularProgressIndicator(),
            );
          case ConnectionState.done:
            var data = snapshot.data;
            if (snapshot.hasData && !snapshot.hasError) {
              return getDashBody(data);
            } else if (data == null) {
              return Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Text("Timeout! Log back in to continue"),
                    Padding(
                      padding: EdgeInsets.all(25.0),
                    ),
                    RaisedButton(
                      onPressed: () {
                        setState(() {
                          token = null;
                        });
                        Navigator.of(context).pushReplacement(
                          CupertinoPageRoute(
                              builder: (BuildContext context) => LoginPage()),
                        );
                      },
                      child: Text('Login Again!'),
                    ),
                  ],
                ),
              );
            } else {
              getRefreshScaffold();
            }
        }
      },
    );
  }
}
cnh2zyt3

cnh2zyt31#

基本示例

下面是StatefulWidget的State类,其中:

  • ListView被 Package 在RefreshIndicator
  • numbersList状态变量是其数据源
  • onRefresh调用_pullRefresh函数以更新数据和ListView
  • _pullRefresh是异步函数,不返回任何内容(Future<void>
  • _pullRefresh的长时间运行的数据请求完成时,在setState()调用中更新numbersList成员/状态变量,以重建ListView,从而显示新数据,
import 'package:flutter/material.dart';
import 'dart:math';

class PullRefreshPage extends StatefulWidget {
  const PullRefreshPage();

  @override
  State<PullRefreshPage> createState() => _PullRefreshPageState();
}

class _PullRefreshPageState extends State<PullRefreshPage> {
  List<String> numbersList = NumberGenerator().numbers;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: _pullRefresh,
        child: ListView.builder(
          itemCount: numbersList.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(numbersList[index]),
            );
          },),
      ),
    );
  }

  Future<void> _pullRefresh() async {
    List<String> freshNumbers = await NumberGenerator().slowNumbers();
    setState(() {
      numbersList = freshNumbers;
    });
    // why use freshNumbers var? https://stackoverflow.com/a/52992836/2301224
  }
}

class NumberGenerator {
  Future<List<String>> slowNumbers() async {
    return Future.delayed(const Duration(milliseconds: 1000), () => numbers,);
  }

  List<String> get numbers => List.generate(5, (index) => number);

  String get number => Random().nextInt(99999).toString();
}

备注

  • 如果您的异步onRefresh函数很快就完成了,您可能希望在它后面添加一个await Future.delayed(Duration(seconds: 2));,这样用户体验会更好。
  • 这为用户提供了时间来完成滑动/下拉手势,并为刷新指示器提供了时间来呈现/动画化/旋转指示数据已被获取。

FutureBuilder范例

下面是使用FutureBuilder的上述State<PullRefreshPage>类的另一个版本,这在从数据库或HTTP源获取数据时很常见:

class _PullRefreshPageState extends State<PullRefreshPage> {
  late Future<List<String>> futureNumbersList;

  @override
  void initState() {
    super.initState();
    futureNumbersList = NumberGenerator().slowNumbers();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<String>>(
        future: futureNumbersList,
        builder: (context, snapshot) {
          return RefreshIndicator(
            child: _listView(snapshot),
            onRefresh: _pullRefresh,
          );
        },
      ),
    );
  }

  Widget _listView(AsyncSnapshot snapshot) {
    if (snapshot.hasData) {
      return ListView.builder(
        itemCount: snapshot.data.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(snapshot.data[index]),
          );
        },);
    }
    else {
      return Center(
        child: Text('Loading data...'),
      );
    }
  }

  Future<void> _pullRefresh() async {
    List<String> freshNumbers = await NumberGenerator().slowNumbers();
    setState(() {
      futureNumbersList = Future.value(freshNumbers);
    });
  }
}

备注

  • slowNumbers()函数与上述基本示例中的函数相同,但数据被 Package 在Future.value()中,因为FutureBuilder需要Future,但setState() * 不 * 应等待异步数据
  • 根据Rémi、柯林和其他Dart/Flutter半神的说法,在其长时间运行的异步数据获取函数完成后,setState()(FutureBuilder示例中为futureNumbersList,Basic示例中为numbersList)内更新Stateful Widget成员变量是一个很好的做法。
  • 请参阅https://stackoverflow.com/a/52992836/2301224
  • 如果您尝试将setState设置为async,则会出现异常
  • 更新setState之外的成员变量并具有空的setState闭包,可能会在将来导致握手/代码分析警告
irlmq6kh

irlmq6kh2#

不确定未来,但对于刷新指标,您必须返回一个void,因此使用类似于

RefreshIndicator(
                onRefresh: () async  {
                  await getData().then((lA) {
                    if (lA is Future) {
                      setState(() {
                        reportList = lA;
                      });
                      return;
                    } else {
                      setState(() {
                       //error
                      });
                      return;
                    }
                  });

                  return;
                },

试试这个,让我知道!

编辑:

好吧,那就试试这个在你里面刷新的方法吧

setState(() {
            reportList = getReport();  
          });
          return reportList;
zd287kbt

zd287kbt3#

试试这个:

onRefresh: () {
  setState(() {});
}}

而不是onRefresh:getReport
reportList字段是Future,它只返回一次值。因此,当您再次调用getReport时,它不会发生任何变化。实际上,更正确的做法是使用StreamStreamBuilder,而不是FutureFutureBuilder。但对于此代码,这可能是最短的解决方案。

djmepvbi

djmepvbi4#

简易法:您可以只使用“下拉”来刷新包-https://pub.dev/packages/pull_to_refresh

trnvg8h3

trnvg8h35#

在不可滚动列表视图中,RefreshIndicator不起作用,因此您必须使用Stack Package 小部件,以实现下拉刷新。

RefreshIndicator(
  onRefresh: () {
  // Refresh Functionality 
  },
  child: Stack(
            children: [
              ListView(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                children: [
                  SizedBox(
                    height: MediaQuery.of(context).size.height,
                  )
                ],
              ),
              // Your Widget 
            ],
          );
        ),

相关问题