英文:
Why is my code stuck on CircularProgressIndicator()
问题
以下是您提供的代码的翻译部分:
import 'package:app/logic/models/http.dart';
import 'package:app/screens/myhomepage.dart';
import 'logic/models/user.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({super.key});
Http http = Http();
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: Stream.fromFuture(
http.makeUserGetRequest(),
),
builder: (context, response) {
if (!response.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (response.hasError) {
return Center(
child: Text('${response.error}'),
);
} else {
return MultiProvider(
providers: [
Provider<List<User>?>.value(value: response.data),
],
child: MaterialApp(
title: 'Flutter Rest Api',
theme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.orange,
),
home: const MyHomePage(),
),
);
}
},
);
}
}
这是主要的Flutter应用程序代码,用于从REST API获取用户数据并显示在界面上。
以下是HTTP请求部分的翻译:
import 'dart:convert';
import './user.dart';
import '../BO/bo.dart';
import 'dart:async';
class Http {
// localhost || 10.0.2.2 (mysql for Android Emulator)
final url = 'localhost:8000/';
final users = 'users/';
final headers = {'Content-type': 'application/json'};
final encoding = Encoding.getByName('utf-8');
Http();
Future<List<User>> makeUserGetRequest() async {
http.Response response = await http.get(Uri.parse('$url$users'));
List<User> result = List<User>.from(
json.decode(response.body).map((json) => User.fromJson(json)),
);
result.sort((a, b) => a.id.compareTo(b.id));
print(getStatusCode(response.statusCode));
return result;
}
makeUserPostRequest(User user) async {
String body = json.encode(user.toJson());
http.Response response = await http.post(
Uri.parse('$url$users'),
headers: headers,
encoding: encoding,
body: body,
);
print((response.body));
print(
'response status ${response.statusCode} => ${getStatusCode(response.statusCode)}');
}
makeUserPutRequest(User user) async {
String body = json.encode(user.toJson());
http.Response response = await http.put(Uri.parse('$url$users${user.id}'),
headers: headers, encoding: encoding, body: body);
print((response.body));
print(
'response status ${response.statusCode} => ${getStatusCode(response.statusCode)}');
}
makeUserDeleteRequest(User user) async {
http.Response response =
await http.delete(Uri.parse('$url$users${user.id}'), headers: headers);
print((response.body));
print(
'response status ${response.statusCode} => ${getStatusCode(response.statusCode)}');
}
}
这部分代码用于与REST API进行通信,包括获取、创建、更新和删除用户数据。
至于您的问题,您提到在模拟器或物理设备上运行应用程序时只能看到一个"圆形进度指示器"小部件。这可能是因为应用程序正在等待从API获取数据,并且在数据准备好之前显示了进度指示器。
要解决此问题,您可以考虑以下几点:
-
确保您的API端点(
$url$users
)是正确的,并且服务器正在运行且可访问。 -
检查网络连接,确保您的设备能够访问API服务器。
-
在应用程序中添加错误处理,以便能够捕获和处理API调用中的错误。您可以在
makeUserGetRequest
等方法中添加更多的错误处理代码,以帮助诊断问题。 -
如果您的API调用需要身份验证或令牌,请确保您已正确配置它们。
-
使用调试工具(例如Flutter DevTools)来跟踪应用程序的网络请求和响应,以便更好地理解问题所在。
通过检查这些方面,您应该能够找到并解决导致应用程序显示进度指示器而不获取数据的问题。希望这些提示对您有所帮助!
英文:
import 'package:app/logic/models/http.dart';
import 'package:app/screens/myhomepage.dart';
import 'logic/models/user.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({super.key});
Http http = Http();
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: Stream.fromFuture(
http.makeUserGetRequest(),
),
builder: (context, response) {
if (!response.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (response.hasError) {
return Center(
child: Text('${response.error}'),
);
} else {
return MultiProvider(
providers: [
Provider<List<User>?>.value(value: response.data),
],
child: MaterialApp(
title: 'Flutter Rest Api',
theme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.orange,
),
home: const MyHomePage(),
),
);
}
},
);
}
}
This is my main and the below code is http file import 'package:http/http.dart' as http;
import 'dart:convert';
import './user.dart';
import '../BO/bo.dart';
import 'dart:async';
class Http {
//localhost || 10.0.2.2 (mysql for Android Emulator)
final url = 'localhost:8000/';
final users = 'users/';
final headers = {'Content-type': 'application/json'};
final encoding = Encoding.getByName('utf-8');
Http();
Future<List<User>> makeUserGetRequest() async {
http.Response response = await http.get(Uri.parse('$url$users'));
List<User> result = List<User>.from(
json.decode(response.body).map((json) => User.fromJson(json)),
);
result.sort((a, b) => a.id.compareTo(b.id));
print(getStatusCode(response.statusCode));
return result;
}
makeUserPostRequest(User user) async {
String body = json.encode(user.toJson());
http.Response response = await http.post(
Uri.parse('$url$users'),
headers: headers,
encoding: encoding,
body: body,
);
print((response.body));
print(
'response status ${response.statusCode} => ${getStatusCode(response.statusCode)}');
}
makeUserPutRequest(User user) async {
String body = json.encode(user.toJson());
http.Response response = await http.put(Uri.parse('$url$users${user.id}'),
headers: headers, encoding: encoding, body: body);
print((response.body));
print(
'response status ${response.statusCode} => ${getStatusCode(response.statusCode)}');
}
makeUserDeleteRequest(User user) async {
http.Response response =
.
3await http.delete(Uri.parse('$url$users${user.id}'), headers: headers);
print((response.body));
print(
'response status ${response.statusCode} => ${getStatusCode(response.statusCode)}');
}
}
I am trying to make restful api using node.js as server, mysql as database and flutter as frontend.
I have checked my backend using Postman and it is working fine but once I try to run the app on either emulator or physical device I am just getting a Circular Progress Indicator Widget.
What is wrong and how do I solve this? Please do tell. I am new to API and Backend.
答案1
得分: 0
我倾向于在处理StreamBuilder或FutureBuilder时反转逻辑,以便在没有捕获的任何情况下显示进度指示器。
也为什么将一个Future转换为一个流,当已经存在FutureBuilder?
```Dart
英文:
I tend to flip the logic when dealing with StreamBuilder or FutureBuilder, so that in any situation that is not caught it is displaying a progress indicator.
...
Widget build(BuiildContext context) {
return StreamBuilder(
stream: Stream.formFuture(http.makeUserGetRequest(),),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
)
}
Also why are converting a future to a stream, when a FutureBuilder exists?
...
Widget build(BuiildContext context) {
return FutureBuilder(
future: http.makeUserGetRequest(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论