Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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(),
            ),
          );
        }
      },
    );
  }
}

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
    },
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading