0

I am making an app to search for some items on goggle.

While doing this search app shows a loading icon, after search is complete it goes to the second screen.

If I press go back to do another search, loading icon still running.

!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(),
    ),

To solve this problem tried to use global variables, as explained in Global Variables in Dart but it didn't work.


globals.dart

library my_prj.globals;

bool isLoading;


main.dart

import 'globals.dart' as global;

!global.isLoading?FlatButton(...

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


result_screen.dart

import 'globals.dart' as global;

global.isLoading = false;

...

I can show more parts of my code if necessary.

pedro_bb7
  • 1,601
  • 3
  • 12
  • 28

1 Answers1

1

You don't need global variable to achieve this use life cycle methods(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,
      ),
    );
  }
}

This deactivate method will be called when this widget is popped or in normal terms when you navigate to a different page. In the deactivate method I have set isLoading=false, So when you navigate to the next page isloading becomes false.

UTKARSH Sharma
  • 698
  • 1
  • 8
  • 17