Home > Software design >  Flutter "bad state: stream has already been listened to" API not running
Flutter "bad state: stream has already been listened to" API not running

Time:04-26

I'm trying to run an application that runs an API from "api-football" (https://www.api-football.com) and getting the error "Bad state: stream has already been listened to".

I'm using the class FutureBuilder and the htpp package.

My main.dart:


// ignore_for_file: prefer_const_constructors

import 'package:flutter/material.dart';
import 'package:placar_brasileirao/api_manager.dart';
import 'package:placar_brasileirao/page_body.dart';
import 'package:placar_brasileirao/soccermodel.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
  return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            'BRASILEIRÃO 2022',
            style: TextStyle(color: Colors.black),
          ),
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        body: FutureBuilder<SoccerMatch>(
            future: SoccerApi().fetchSoccerMatch(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasData) {
                print((snapshot.data).length);
                return PageBody(snapshot.data);
              } else if (snapshot.hasError) {
                return Center(
                  child: Text('${snapshot.error}'),
                );
              }
              return Center(
                child: CircularProgressIndicator(),
              );
            }),
      ),
    );
  }
}

The file that I manage the API:

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:placar_brasileirao/soccermodel.dart';



class SoccerApi {

  Future<SoccerMatch> fetchSoccerMatch() async {
    var headers = {
      'x-rapidapi-host': 'v3.football.api-sports.io',
      'x-rapidapi-key': 'c15180946e4982c30d9b63bc534d5f3c'
    };

    var request = http.Request('GET', Uri.parse('https://v3.football.api-sports.io/fixtures/rounds?season=2021&league=39'));

    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();


    if (response.statusCode == 200) {
      print(await response.stream.bytesToString());
      return SoccerMatch.fromJson(jsonDecode(await response.stream.bytesToString()));
    }
    else {
      print(response.reasonPhrase);
      throw Exception('Failed to load album');
    }
  }
}

The code is running but its not returning my "PageBody"

https://i.stack.imgur.com/SAvK5.png

CodePudding user response:

This is happening because you are listening for response.stream two times. Try to listen one time and store result in a variable.

if (response.statusCode == 200) {
      final responseData = await response.stream.bytesToString();
      print(responseData);
      return SoccerMatch.fromJson(jsonDecode(responseData));
}
  • Related