gpt4 book ai didi

加载数据时 Flutter 更改 Body Widget

转载 作者:IT王子 更新时间:2023-10-29 07:23:26 26 4
gpt4 key购买 nike

我是 Flutter 的新手,在我的应用程序中,我想在从后端获取数据时显示 ProgressBar 指示器小部件,并在获取数据时显示另一个信息小部件,我只是不知道该怎么做?

我试过下面的代码,它工作正常!但我不知道这是不是最好的方法

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

class UserLocation extends StatefulWidget {


@override
_UserLocationState createState() => _UserLocationState();
}



class _UserLocationState extends State<UserLocation> {

bool isLoading;

@override
void initState() {
isLoading = true;
getData();
super.initState();
}
@override
Widget build(BuildContext context) {
return makeBody(

);
}


Widget indicator(){
return Scaffold(

backgroundColor: Colors.red,

);
}

Widget showData(){
return Scaffold(

backgroundColor: Colors.green,

);
}

Widget makeBody(){
if(isLoading){
return this.indicator();
}else{
return this.showData();
}
}

Future getData() async{

var response = await http.get(Uri.encodeFull('http://xxxx'));
if(response.statusCode == 200){
isLoading = false;
setState(() {
var jsonResponse = convert.jsonDecode(response.body);
var data = jsonResponse['data'] as List;
print(data);
});


}else{
isLoading = false;
print("Request failed with status: ${response.statusCode}.");
}

}
}

任何帮助,想法将不胜感激

最佳答案

我认为您从 API 获得的响应代码不是 200,并且当响应不是 200 时您没有使用 setState

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

class UserLocation extends StatefulWidget {


@override
_UserLocationState createState() => _UserLocationState();
}



class _UserLocationState extends State<UserLocation> {

bool isLoading;

@override
void initState() {
isLoading = true;
getData();
super.initState();
}
@override
Widget build(BuildContext context) {
return makeBody(

);
}


Widget indicator(){
return Scaffold(

backgroundColor: Colors.red,

);
}

Widget showData(){
return Scaffold(

backgroundColor: Colors.green,

);
}

Widget makeBody(){
if(isLoading){
return this.indicator();
}else{
return this.showData();
}
}

Future getData() async{

var response = await http.get(Uri.encodeFull('http://xxxx'));
if(response.statusCode == 200){

setState(() {
isLoading = false;
var jsonResponse = convert.jsonDecode(response.body);
var data = jsonResponse['data'] as List;
print(data);
});


}else{
setState(() {
isLoading = false;
});


print("Request failed with status: ${response.statusCode}.");
}

}
}

关于加载数据时 Flutter 更改 Body Widget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54349290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com