gpt4 book ai didi

flutter - 在 Flutter 中下拉到 REFRESH

转载 作者:行者123 更新时间:2023-12-03 02:40:16 25 4
gpt4 key购买 nike

我的仪表板代码如下所示,
这里我在 getReport 方法中做 get req,我添加了 RefreshIndicator在容器内下拉时应该进行刷新的代码中,我正在调用我的 getData(),但我没有得到刷新的内容,我在下面添加我的代码,让我知道我是否在任何地方犯了错误。

在我的dashboard.dart下方

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();
}
}
},
);
}
}

最佳答案

基本示例

下面是一个 StatefulWidget 的 State 类,其中:

  • 一个 ListView包裹在 RefreshIndicator
  • words状态变量是它的数据源
  • onRefresh来电_pullRefresh更新 ListView 的函数
  • _pullRefresh是一个异步函数,不返回任何内容 (a Future<void> )
  • _pullRefresh的长时间运行的数据请求完成,words成员/状态变量在 setState() 中更新调用重建ListView显示新数据
  • import 'package:english_words/english_words.dart';

    class _PullToRefreshPageState extends State<PullToRefreshPage> {
    List<WordPair> words = generateWordPairs().take(5).toList();

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

    Future<void> _pullRefresh() async {
    List<WordPair> freshWords = await WordDataSource().getFutureWords(delay: 2);
    setState(() {
    words = freshWords;
    });
    // why use freshWords var? https://stackoverflow.com/a/52992836/2301224
    }
    }

    class WordDataSource {
    Future<List<WordPair>> getFutureWords({int size = 5, int delay = 5}) async {
    await Future.delayed(Duration(seconds: delay));
    return generateWordPairs().take(5).toList();
    }
    }

    笔记
  • 如果你的异步 onRefresh功能很快完成,您可能需要添加 await Future.delayed(Duration(seconds: 2));在它之后,只是让用户体验更愉快。
  • 这为用户提供了完成滑动/下拉手势和刷新指示器呈现/动画/旋转指示数据已被获取的时间。


  • FutureBuilder 示例

    这是另一个示例,使用 FutureBuilder,这在从数据库或 HTTP 源获取数据时很常见
    class _PullToRefreshFuturePageState extends State<PullToRefreshPage> {
    Future<List<WordPair>> futureWords;

    @override
    void initState() {
    super.initState();
    futureWords = WordDataSource().getFutureWords(delay: 2);
    }

    @override
    Widget build(BuildContext context) {
    return FutureBuilder<List<WordPair>>(
    //initialData: [],
    future: futureWords,
    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].asPascalCase),
    );
    },);
    }
    else {
    return Center(
    child: Text('Loading data...'),
    );
    }
    }

    Future<void> _pullRefresh() async {
    List<WordPair> freshFutureWords = await WordDataSource().getFutureWords(delay: 2);
    setState(() {
    futureWords = Future.value(freshFutureWords);
    });
    }
    }

    笔记
  • getFutureWords()功能与 中的相同基本示例 上面,但数据包含在 Future.value() 中因为 FutureBuilder 期望 Future
  • 根据 Rémi、Collin 和其他 Dart/Flutter 半神人的说法,更新 Stateful Widget 成员变量是一种很好的做法 里面 setState() (futureWords 在 FutureBuilder 示例中和 words 在 Basic 示例中),在其长时间运行的异步数据获取功能完成之后。
  • https://stackoverflow.com/a/52992836/2301224
  • 如果您尝试设置 setState async , 你会得到一个异常(exception)
  • 更新 setState 之外的成员变量并且有一个空的setState关闭,将来可能会导致打手/代码分析警告
  • 关于flutter - 在 Flutter 中下拉到 REFRESH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57972505/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com