每当页面在屏幕上时如何重新加载页面-Flutter [英] How to reload the page whenever the page is on screen - flutter
问题描述
每次在屏幕上可见页面时,在flutter中是否有可用的回调?在ios中,有一些委托方法,例如 viewWillAppear
, viewDidAppear
, viewDidload
.
Is there any callbacks available in flutter for every time the page is visible on screen? in ios there are some delegate methods like viewWillAppear
, viewDidAppear
, viewDidload
.
我想在屏幕上显示特定页面时调用API调用.
I would like to call a API call whenever the particular page is on-screen.
注意:我不是在询问应用程序的状态,例如前景,背景,暂停,恢复.
Note: I am not asking the app states like foreground, backround, pause, resume.
谢谢!
推荐答案
每次显示屏幕时,您都不需要 StatefulWidget
来调用api.
You don't need StatefulWidget
for calling the api everytime the screen is shown.
在以下示例代码中,按浮动动作按钮导航到api调用屏幕,使用后退箭头返回,再次按浮动动作按钮导航到api页面.
In the following example code, press the floating action button to navigate to api calling screen, go back using back arrow, press the floating action button again to navigate to api page.
每次访问此页面api都会自动调用.
Everytime you visit this page api will be called automatically.
import 'dart:async';
import 'package:flutter/material.dart';
main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => ApiCaller())),
),
);
}
}
class ApiCaller extends StatelessWidget {
static int counter = 0;
Future<String> apiCallLogic() async {
print("Api Called ${++counter} time(s)");
await Future.delayed(Duration(seconds: 2));
return Future.value("Hello World");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Api Call Count: $counter'),
),
body: FutureBuilder(
future: apiCallLogic(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) return const CircularProgressIndicator();
if (snapshot.hasData)
return Text('${snapshot.data}');
else
return const Text('Some error happened');
},
),
);
}
}
这是带有零样板的简单代码.
This is the simple code with zero boiler-plate.
这篇关于每当页面在屏幕上时如何重新加载页面-Flutter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!