'streamBuilder flutter doesn't display data

im using streamBuilder to rebuild my screen depend on the project_id selected by taping on the project widget i send project_id to the next screen with constructer the streamBuilder read that constructor well but doesnt display that fetched from the http response from django endpoint here the model and api

// To parse this JSON data, do
//
//     final task = taskFromJson(jsonString);
import 'dart:collection';
import 'dart:core';
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:project/model/project_model.dart';
import 'package:project/tasksById.dart';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';

//List<Task> taskFromJson(String str) => List<Task>.from(json.decode(str).map((x) => Task.fromJson(x)));

//String taskToJson(List<Task> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Task {
  String? url;
  int? id;
  String? owner;
  String? project;
  String? title;
  DateTime? start;
  DateTime? end;
  String? desc;
  int? project_id;

  Task(
      {this.url,
      this.id,
      this.owner,
      this.project,
      this.title,
      this.start,
      this.end,
      this.desc,
      this.project_id});

  
  factory Task.fromJson(Map<String, dynamic> json) => Task(
    url :json["url"],
    id: json["id"],
    owner: json["owner"],
    project: json["project"],
    title: json["title"],
    start: DateTime.parse(json["start"]),
    end: DateTime.parse(json["end"]),
    desc: json["desc"],
    project_id: json["project_id"],
    
    
  );

  Map<String, dynamic> toJson() => {
    "url": url,
    "id": id,
    "owner": owner,
    "project": project, 
    "title": title,
    "start": start?.toIso8601String(),
    "end": end?.toIso8601String(),
    "desc": desc,
    "project_id": project_id,
  };
}
  class SharedProojectId {
  Future<Future<bool>> setid(int? newId) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setInt("project_id", newId!);
  }

  Future<int> getid() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getInt("project_id")??0;
  }
}
class TaskProvider with ChangeNotifier{
     
  TaskProvider(){
    int project_id;
     SharedProojectId().getid().then((data) async {
      project_id = data;
      
    //  SharedProojectId().getid()as int;
     //TaskById(project_id: 1 /*widget.project_id*/, titleP: '',).project_id;
     print('coming id is $project_id');
     await this.fetchTask(project_id);

     });
  }
  

  List<Task> _task = [];
  List<Task> get task {
    return [..._task];
  }

    void addTask(Task task) async {
    final response = await http.post(Uri.parse('http://mostafahamed.pythonanywhere.com/project/task'),
        headers: {"Content-Type": "application/json"}, body: json.encode(task));
    if (response.statusCode == 201) {
      task.id = json.decode(response.body)['id'];
      _task.add(task);
      notifyListeners();
      print('suceeed add ed task');
      print(response.body);
    }else{
      print(response.body);
       print('failed add ed task');
    }
  }

  void deleteTask(Task task) async {
    final response =
        await http.delete(Uri.parse('http://mostafahamed.pythonanywhere.com/project/task${task.id}/'));
    if (response.statusCode == 204) {
      _task.remove(task);
      notifyListeners();
    }
  }


     Stream<List<Task>> fetchTask(/*[project_id]*/prpject_id) async*{
     final response = await http
      .get(Uri.parse('http://mostafahamed.pythonanywhere.com/tasks/?format=json'));
    if (response.statusCode==200){
      var data = json.decode(response.body)as List;
      // _task=data.map<Task>((json) => Task.fromJson(json)).toList();
      await Future.delayed(Duration(seconds:3));
      _task=data.map<Task>((json) => Task.fromJson(json))
      .where((task) => task.project_id == prpject_id ).toList();
      notifyListeners();
       print('sucess view task list');
       print(response.body);
       print('$prpject_id in sucess');
       yield _task;
    }
   else {
     print(response.body);
     print(response.statusCode);
     print('$prpject_id in faild');
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load tasks');
    
  }
  }
}

here the the screen where i want to display tasks depend on selected project with futureBuilder using Project_id that i got in the contructor

import 'package:flutter/material.dart';
import 'package:project/model/task_model.dart';
import 'package:project/project_dtetailForTest.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'new_project.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:project/home_page02.dart';
import 'dart:async';

class  TaskById extends StatefulWidget {
  //const TaskById({ Key? key }) : super(key: key);
  final int project_id;
  final String? titleP;
  
  //final Task task =Task();
  TaskById({Key? key,  required this.project_id,required this.titleP}):super(key: key);
  @override
  State<TaskById> createState() => _TaskByIdState();
}

class _TaskByIdState extends State<TaskById> {
  late Stream _getDash;
@override
void initState() {
    // TODO: implement initState
    super.initState();
    _getDash = TaskProvider().fetchTask(widget.project_id).asBroadcastStream();
}
  @override
  Widget build(BuildContext context) {
    final taskP= Provider.of<TaskProvider>(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        bottom: PreferredSize(
        child: Container(
         color: const Color(0xff94adb4),
         height: 2,
         width: 320,
      ),
      preferredSize: const Size.fromHeight(4.0)),
        centerTitle: true,
        backgroundColor:const Color(0xff076792),
        title:  Text(
          '${widget.titleP}-${widget.project_id}',//projecct name  + id
           style: const TextStyle(color: Colors.white,
             fontSize: 35,
             fontWeight:FontWeight.w700,
             shadows: [
               Shadow(
                  color: Color(0xa6A2B6D4),
                  blurRadius:20),
              ] ),
        ),
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: const Icon(
            Icons.arrow_back,
            size: 44,
          ),
        ),
       actions:[Container(padding: const EdgeInsets.fromLTRB(0, 0, 6, 3),
         child: IconButton(
            color:Colors.white ,
            icon: const Icon(
              Icons.search,
              size: 44,
            ),
            onPressed: () {},
          ),
       ),] 
      ),
      //TaskProvider(){
  //   this.fetchTask();
  // }
      body: StreamBuilder(
        stream: _getDash.asBroadcastStream(),
        // TaskProvider().fetchTask(widget.project_id);
        builder: (context, stream){
          if (stream.hasError) print(stream.error);
          if (!stream.hasData) print(stream.data);
          if (stream.hasData) print("stream vlaue : ${stream.data}");
               print('wdgetP id :  ${widget.project_id}');
          return stream.hasData 
          ? TaskList(task:stream.data as List<Task>, project_id: widget.project_id, titleP: widget.titleP)
          :Center(child: CircularProgressIndicator());
        }),
  
    //    FutureProvider(
    //     create: (context) => TaskProvider().fetchTask() ,
    //     initialData:  [CircularProgressIndicator()],
    //     child:Center(child: Consumer<Task>( 
    //       builder: (context, task, widget) {
    //         return (taskP !=null) ? Column(
    //     children: [
    //       Row(
    //         children:  const [
    //           Padding(padding: EdgeInsets.all(7),
    //            child: Padding(
    //             padding: EdgeInsets.fromLTRB(24,10,10,8),
    //             child: Text('Project1',
    //             style: TextStyle(
    //               color: Color(0xff076792),
    //               fontSize: 40,
    //               fontWeight: FontWeight.w600
    //             ),
    //             ),
    //            ),
    //           ),              
    //         ],
    //       ),
    //       // dynamic list
    //      Expanded(
    //        child: ListView.builder(
    //        itemCount: taskP.task.length ,
    //        itemBuilder: (BuildContext context, int index) {
    //          return  Padding(
    //         padding:  const EdgeInsets.fromLTRB(28, 12, 28, 0),
    //         child: GestureDetector(
    //           onTap: () {
               
    //             Navigator.push(context, MaterialPageRoute(builder: (context) => projectDetails()));
    //           },
    //            child: Card(child:Container(padding: const EdgeInsets.fromLTRB(18,8,9,4),
    //             width: 100,
    //             height: 100,
    //              decoration: BoxDecoration(
    //              borderRadius: BorderRadius.circular(19.0),
    //               color: const Color(0xff076792),
    //               boxShadow:  const [
    //               BoxShadow(color: Colors.black, spreadRadius: 1),
    //               BoxShadow(color: Color(0xa6A2B6D4),               
    //                  offset: Offset(7,5),
    //                  blurRadius:20),
    //               ],
    //               ),
    //             child: Column(children: [
    //               Row(mainAxisAlignment: MainAxisAlignment.start,
    //                 children: [
    //                   Text('Starting '+taskP.task[index].start.toString(),style:
    //                     const TextStyle(color: Color.fromARGB(255, 133, 186, 202),fontSize: 18,),
    //                    ),
    //                 ],
    //               ),
    //               const Spacer(),
    //               Row(mainAxisAlignment: MainAxisAlignment.center,
    //                 children: [
    //                   Text(taskP.task[index].title??'',style:
    //                    const TextStyle(color: Colors.white,fontSize: 34,)),
    //                 ],
    //               ),
    //               const Spacer(),
    //               Row(mainAxisAlignment: MainAxisAlignment.end,
    //                 children: [
    //                   Text('Ending '+taskP.task[index].end.toString(),style:
    //                    const TextStyle(color: Color.fromARGB(255, 133, 186, 202),
    //                    fontSize: 18,
    //                    )),
    //                 ],
    //               ),
    //             ]),
    //           ),),
    //         ),
    //       );
    //        }),
    //      )
    //      ],
    //   )
    //         : CircularProgressIndicator();
    //       },
    //     ) ,
        
    //     ) 
    // //         widget.project_id),
          
    // //       builder: (context, snapshot){
    // //         if (snapshot.hasError) print(snapshot.error);
    // //         return snapshot.hasData
    // //             ? TaskList(taskP: snapshot.data)
    // //             : Center(child: CircularProgressIndicator());
    // //       }),
    // )
    ); 
  }
}
class TaskList extends StatelessWidget {

  final List <Task> task;
  final int project_id;
  final String? titleP;
  TaskList({Key? key, required this.task,required this.project_id ,required this.titleP}) : super(key: key);
  @override
  Widget build(BuildContext context) {
      final taskP= Provider.of<TaskProvider>(context );
    // TODO: implement build
    return Column(
        children: [
          Row(
            children:   [
              Padding(padding: const EdgeInsets.all(7),
               child: Padding(
                padding: const EdgeInsets.fromLTRB(24,10,10,8),
                child: Text('$titleP-$project_id',
                style: const TextStyle(
                  color: Color(0xff076792),
                  fontSize: 40,
                  fontWeight: FontWeight.w600
                ),
                ),
               ),
              ),              
            ],
          ),
          // dynamic list
         Expanded(
           child: ListView.builder(
           itemCount: taskP.task.length ,
           itemBuilder: (BuildContext context, int index) {
             return  Padding(
            padding:  const EdgeInsets.fromLTRB(28, 12, 28, 0),
            child: GestureDetector(
              onTap: () {
               
                Navigator.push(context, MaterialPageRoute(builder: (context) => projectDetails()));
              },
               child: Card(child:Container(padding: const EdgeInsets.fromLTRB(18,8,9,4),
                width: 100,
                height: 100,
                 decoration: BoxDecoration(
                 borderRadius: BorderRadius.circular(19.0),
                  color: const Color(0xff076792),
                  boxShadow:  const [
                  BoxShadow(color: Colors.black, spreadRadius: 1),
                  BoxShadow(color: Color(0xa6A2B6D4),               
                     offset: Offset(7,5),
                     blurRadius:20),
                  ],
                  ),
                child: Column(children: [
                  Row(mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text('Starting '+taskP.task[index].start.toString(),style:
                        const TextStyle(color: Color.fromARGB(255, 133, 186, 202),fontSize: 18,),
                       ),
                    ],
                  ),
                  const Spacer(),
                  Row(mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(taskP.task[index].title??'',style:
                       const TextStyle(color: Colors.white,fontSize: 34,)),
                    ],
                  ),
                  const Spacer(),
                  Row(mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text('Ending '+taskP.task[index].end.toString(),style:
                       const TextStyle(color: Color.fromARGB(255, 133, 186, 202),
                       fontSize: 18,
                       )),
                    ],
                  ),
                ]),
              ),),
            ),
          );
           }),
         )
         ],
      );
  }
}

addition information : i used future builder and it worked well but i discovered it wasn't good idea to use it here as my screen wont be fixed the data and values are changeable when i converted future builder into stream Builder sure i made some changes but the screen don't show data addition: here is the result of print in console console result

screen 1 on the app projects screen where i choose project widget to display it tasks

screen 2 on the app [after clicking on the project i got the project name and id very easy but task lists doesn't display] 3 id u need more details the code source here https://github.com/alihassan75/project or u can ask for details ..kindly this is important as deadline for send this project close :/



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source