我想在我的应用程序中集成flutter连接检查功能,并且集成后的功能对所有小部件都适用,但是对于我来说,对于setState方法,它不能为isLoading方法。
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool isLoading = true;
Widget result;
RecipeService _recipeService = RecipeService();
List<Recipe> _recipeList = List<Recipe>();
@override
void initState() {
super.initState();
_getRecipe();
checkStatus();
}
_getRecipe() async {
var dayRecipes = await _recipeService.getRecipeOfTheDay();
var _list= json.decode(dayRecipes.body);
List<Recipe> results = [];
_list['data'].forEach((data) {
var model = Recipe();
model.id = data['id'];
model.title = data['recipeTitle'];
model.ingredients = data['recipeIngredient'];
model.directions = data['recipeDirection'];
model.cookTime = data['cookTime'].toString();
model.image = data['recipePhoto'];
results.add(model);
});
setState(() {
_dayRecipeList = results;
isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("My Recipe"),
),
body: Container(
alignment: Alignment.center,
child: result
),
);
}
这是Internet的Check方法,在连接的情况下,我使用homeItems()小部件显示我的内容
void checkStatus() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi) {
result = homeItems();
setState(() {});
} else {
result = Text("Unable to connect. Please Check Internet Connection");
setState(() {});
print("Unable to connect. Please Check Internet Connection");
}
}
这是我的homeItems小部件,在checkStatus方法中使用。作为结果= homeItems();
Widget homeItems(){
Center(
child: isLoading
? CircularProgressIndicator(
backgroundColor: Colors.blue,
strokeWidth: 10,
)
: ListView(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("All Recipes",
style: TextStyle(
fontSize: 25,
color: Colors.red,
fontWeight: FontWeight.bold)),
),
RecipesOfDay(dayRecipeList: _dayRecipeList),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("All Recipes",
style: TextStyle(
fontSize: 25,
color: Colors.red,
fontWeight: FontWeight.bold)),
),
],
),
);
}
}
运行所有应用程序后,我得到黑屏,没有任何错误。请看看以解决此问题。谢谢
答案 0 :(得分:0)
最后尝试使用。并最终将isLoading设置为false