简体   繁体   English

go如何在Flutter返回刷新上一页?

[英]How to go back and refresh the previous page in Flutter?

I have a home page which when clicked takes me to another page through navigates, do some operations in then press the back button which takes me back to the home page.我有一个主页,单击该主页时会通过导航将我带到另一个页面,在其中进行一些操作然后按后退按钮将我带回主页。 but the problem is the home page doesn't get refreshed.但问题是主页没有得到刷新。

Is there a way to reload the page when i press the back button and refreshes the home page?当我按下后退按钮并刷新主页时,有没有办法重新加载页面?

You can trigger the API call when you navigate back to the first page like this pseudo-code当您像此伪代码一样导航回第一页时,您可以触发 API 调用

class PageOne extends StatefulWidget {
  @override
  _PageOneState createState() => new _PageOneState();
}

class _PageOneState extends State<PageOne> {
  _getRequests()async{

  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new RaisedButton(onPressed: ()=>
        Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new PageTwo()),)
        .then((val)=>val?_getRequests():null),
      ),
    ));
  }
}

class PageTwo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //somewhere
    Navigator.pop(context,true);
  }
}

Or you can just use a stream if the API is frequently updated, the new data will be automatically updated inside your ListView或者,如果 API 更新频繁,您可以只使用流,新数据将在您的ListView内自动更新

For example with firebase we can do this例如,使用 firebase 我们可以做到这一点

stream: FirebaseDatabase.instance.reference().child(
      "profiles").onValue

And anytime you change something in the database (from edit profile page for example), it will reflect on your profile page.并且无论何时您更改数据库中的某些内容(例如从编辑个人资料页面),它都会反映在您的个人资料页面上。 In this case, this is only possible because I am using onValue which will keep listening for any changes and do the update on your behalf.在这种情况下,这只是可能的,因为我正在使用onValue它将继续侦听任何更改并代表您进行更新。

(In your 1st page): Use this code to navigate to the 2nd page. (在您的第一页中):使用此代码导航到第二页。

Navigator.pushNamed(context, '/page2').then((_) {
  // This block runs when you have returned back to the 1st Page from 2nd.
  setState(() {
    // Call setState to refresh the page.
  });
});

(In your 2nd page): Use this code to return back to the 1st page. (在您的第 2 页):使用此代码返回到第 1 页。

Navigator.pop(context);

If you are using GetX : use result when you navigate back from nextScreen as follow :如果您使用 GetX :从 nextScreen 导航返回时使用结果,如下所示:

Get.back(result: 'hello');

and to reload previous page use this function :并重新加载上一页使用此功能:

void _navigateAndRefresh(BuildContext context) async {
    final result = await Get.to(()=>NextScreen());
    if(result != null){
      model.getEMR(''); // call your own function here to refresh screen
    }
  }

call this function instead of direct navigation to nextScreen调用此函数而不是直接导航到 nextScreen

Simply i use this:我只是使用这个:

onPressed: () {
          Navigator.pop(context,
              MaterialPageRoute(builder: (context) => SecondPage()));
        },

this to close current page:关闭当前页面:

Navigator.pop

to navigate previous page:浏览上一页:

MaterialPageRoute(builder: (context) => SecondPage())

In FirtsPage, me adding this for refresh on startUpPage:在 FirtsPage 中,我添加了这个以在 startUpPage 上刷新:

 @override
  void initState() {
    //refresh the page here
    super.initState();
  }

The best solution which I found is simply navigating to the previous page: In getx :我发现的最佳解决方案只是导航到上一页:在getx

 return WillPopScope(
      onWillPop: () {
        Get.off(() => const PreviousPage());

        return Future.value(true);
      },
child: YourChildWidget(),

or if you want to use simple navigation then:或者如果你想使用简单的导航,那么:

 Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) =>PreviousPage() ,));

For a more fine-grained, page-agnostic solution I came up with this Android Single LiveEvent mimicked behaviour.对于更细粒度、与页面无关的解决方案,我想出了这个 Android Single LiveEvent模仿行为。

I create such field inside Provider class, like:我在Provider类中创建了这样的字段,例如:

SingleLiveEvent<int> currentYearConsumable = SingleLiveEvent<int>();

It has a public setter to set value.它有一个公共设置器来设置值。 Public consume lets you read value only once if present (request UI refresh).公共consume允许您仅读取一次值(如果存在)(请求 UI 刷新)。 Call consume where you need (like in build method).在你需要的地方调用consume (比如在build方法中)。

You don't need Provider for it, you can use another solution to pass it.您不需要Provider ,您可以使用其他解决方案来传递它。

Implementation:执行:

/// Useful for page to page communication
/// Mimics Android SingleLiveEvent behaviour
/// https://stackoverflow.com/questions/51781176/is-singleliveevent-actually-part-of-the-android-architecture-components-library
class SingleLiveEvent<T> {
  late T _value;
  bool _consumed = true;

  set(T val) {
    _value = val;
    _consumed = false;
  }

  T? consume() {
    if (_consumed) {
      return null;
    } else {
      _consumed = true;
      return _value;
    }
  }
}

await the navigation and then call the api function.等待导航,然后调用 api 函数。

await Navigator.of(context).pop();等待 Navigator.of(context).pop(); await api call等待 api 调用

You can do this with a simple callBack that is invoked when you pop the route.您可以使用弹出路由时调用的简单回调来执行此操作。 In the below code sample, it is called when you pop the route.在下面的代码示例中,它会在您弹出路由时调用。

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  _someFunction()async{
      Navigator.of(context).push(MaterialPageRoute(builder: (_)=> PageTwo(
         onClose():(){
            // Call setState here to rebuild this widget
            // or some function to refresh data on this page.
         }
     )));
   }

 @override
  Widget build(BuildContext context) {
     return SomeWidget();
 }
...
} // end of widget
class PageTwo extends StatelessWidget {
  final VoidCallback? onClose;
  PageTwo({Key? key, this.onClose}) : super(key: key);

  @override
  Widget build(BuildContext context) {
   
   return SomeWidget(
    onEvent():{ 
     Navigate.of(context).pop();
     onClose(); // call this wherever you are popping the route
   );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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