首页 > 解决方案 > 当我按下返回主屏幕(登录页面)时,加载图标仍在运行

问题描述

我正在制作一个应用程序来搜索护目镜上的一些项目。

在执行此搜索应用程序时会显示一个加载图标,搜索完成后会转到第二个屏幕。

如果我按返回进行另一次搜索,加载图标仍在运行。

!isLoading ? FlatButton(
    color: Colors.blue,
    textColor: Colors.white,
    disabledColor: Colors.grey,
    disabledTextColor: Colors.black,
    padding: EdgeInsets.all(8.0),
    splashColor: Colors.blueAccent,
    onPressed: () async{
        String query = getQuery();
        List<Recipe> receitas = await getReceitas(query);
        Navigator.push(context, MaterialPageRoute(builder: (context)=>result_screen(receitas)));
        setState(() {
            isLoading = true;
        });
    },
    child: Text('BUSCAR', style: TextStyle(fontSize: 15.0))):
    Center(
              child: CircularProgressIndicator(),
    ),

为了解决这个问题,尝试使用全局变量,如Dart 中的全局变量中所述,但它不起作用。


globals.dart

library my_prj.globals;

bool isLoading;


主要.dart

import 'globals.dart' as global;

!global.isLoading?FlatButton(...

setState(() {
     global.isLoading = true;
});


result_screen.dart

import 'globals.dart' as global;

global.isLoading = false;

...

如有必要,我可以显示我的代码的更多部分。

标签: flutterdart

解决方案


你不需要全局变量来实现这个使用生命周期方法(deactivate())

class Temp extends StatefulWidget {
  @override
  _TempState createState() => _TempState();
}

class _TempState extends State<Temp> {

  bool isLoading=false;

    void deactivate() {       //Life cycle method
    isLoading=false;
    super.deactivate();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.yellow,
      ),
    );
  }
}

这个 deactivate 方法将在弹出这个小部件时调用,或者在正常情况下,当您导航到不同的页面时调用。在 deactivate 方法中我设置了 isLoading=false,所以当您导航到下一页时,isloading 变为 false。


推荐阅读