为什么我的代码停在CircularProgressIndicator()上?

huangapple go评论74阅读模式
英文:

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获取数据,并且在数据准备好之前显示了进度指示器。

要解决此问题,您可以考虑以下几点:

  1. 确保您的API端点($url$users)是正确的,并且服务器正在运行且可访问。

  2. 检查网络连接,确保您的设备能够访问API服务器。

  3. 在应用程序中添加错误处理,以便能够捕获和处理API调用中的错误。您可以在makeUserGetRequest等方法中添加更多的错误处理代码,以帮助诊断问题。

  4. 如果您的API调用需要身份验证或令牌,请确保您已正确配置它们。

  5. 使用调试工具(例如Flutter DevTools)来跟踪应用程序的网络请求和响应,以便更好地理解问题所在。

通过检查这些方面,您应该能够找到并解决导致应用程序显示进度指示器而不获取数据的问题。希望这些提示对您有所帮助!

英文:
import &#39;package:app/logic/models/http.dart&#39;;
import &#39;package:app/screens/myhomepage.dart&#39;;
import &#39;logic/models/user.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:provider/provider.dart&#39;;
import &#39;dart:async&#39;;

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(&#39;${response.error}&#39;),
          );
        } else {
          return MultiProvider(
            providers: [
              Provider&lt;List&lt;User&gt;?&gt;.value(value: response.data),
            ],
            child: MaterialApp(
              title: &#39;Flutter Rest Api&#39;,
              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 &#39;dart:convert&#39;;
import &#39;./user.dart&#39;;
import &#39;../BO/bo.dart&#39;;
import &#39;dart:async&#39;;

class Http {
  //localhost || 10.0.2.2 (mysql for Android Emulator)
  final url = &#39;localhost:8000/&#39;;
  final users = &#39;users/&#39;;
  final headers = {&#39;Content-type&#39;: &#39;application/json&#39;};
  final encoding = Encoding.getByName(&#39;utf-8&#39;);
  Http();

  Future&lt;List&lt;User&gt;&gt; makeUserGetRequest() async {
    http.Response response = await http.get(Uri.parse(&#39;$url$users&#39;));
    List&lt;User&gt; result = List&lt;User&gt;.from(
      json.decode(response.body).map((json) =&gt; User.fromJson(json)),
    );
    result.sort((a, b) =&gt; 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(&#39;$url$users&#39;),
      headers: headers,
      encoding: encoding,
      body: body,
    );
    print((response.body));
    print(
        &#39;response status ${response.statusCode} =&gt; ${getStatusCode(response.statusCode)}&#39;);
  }

  makeUserPutRequest(User user) async {
    String body = json.encode(user.toJson());
    http.Response response = await http.put(Uri.parse(&#39;$url$users${user.id}&#39;),
        headers: headers, encoding: encoding, body: body);
    print((response.body));
    print(
        &#39;response status ${response.statusCode} =&gt; ${getStatusCode(response.statusCode)}&#39;);
  }

  makeUserDeleteRequest(User user) async {
    http.Response response =
        .
3await http.delete(Uri.parse(&#39;$url$users${user.id}&#39;), headers: headers);
    print((response.body));
    print(
        &#39;response status ${response.statusCode} =&gt; ${getStatusCode(response.statusCode)}&#39;);
  }
}

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(&quot;${snapshot.error}&quot;);
      }
      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(&quot;${snapshot.error}&quot;);
      }
      return CircularProgressIndicator();
    },
  )
}

huangapple
  • 本文由 发表于 2023年6月19日 01:19:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定