I am checking the connectivity using Connectivity().checkConnectivity()
it is working but the setState()
is not calling when I navigate to this page.
To navigate to main page to another page I am using Navigator.push(context, MaterialPageRoute(builder: (context) => search()));
and here is my next page
class search extends StatefulWidget {
@override
_searchState createState() => _searchState();
}
class _searchState extends State<search> {
List<filter> _list = [];
List<filter> to_display = [];
bool isoffline;
Future<void> connectivity() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network.
setState(() {
isoffline = true;
});
print("connected");
} else if (connectivityResult == ConnectivityResult.wifi) {
setState(() {
isoffline = true;
});
// I am connected to a wifi network.
print("connected");
} else {
setState(() {
isoffline = false;
});
print(
"dissconneteddsfffffffffffffffffffffffffffffffffffffffffffffffffffffffdsfsd");
}
}
Future _future;
@override
void initState() {
mylist().then((value) {
setState(() {
_list = to_display = value;
});
});
connectivity();
print("value${isoffline}"); // this value is on null
_future = data();
super.initState();
}
print("value${isoffline}");
// this value is on null
Solution 1: Midhun MP
The function connectivity is an asynchronous function. You are calling the function and immediately checking the boolean value, that's why you are getting null. You have to wait till the execution, either by using await or then syntax.
connectivity().then((value) {
print("value ${isoffline}");
});
Solution 2: GJJ2019
In your code connectivity();
method is async
which mean it will require some time to complete.
Now when init
method is called it executes connectivity();
and then immediately executes print("value${isoffline}");
now the value for isoffline
initially is null
, hence null
printed
solution is either you put print("value${isoffline}");
in connectivity();
method or try to add it after build
method.
@override
Widget build(BuildContext context) {
connectivity();
print("value${isoffline}");
return YourWidget();
}