streamBuilder flutter doesn't display data - android

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 :/

Related

If else statement not showing proper output in Flutter

I am following a course video from YouTube to design a shopping cart in Flutter. But according to the course video, I am supposed to see the output showing the pictures of the items, their prices, units, and other details [shown in picture 1]. But in my output I am seeing nothing but only the AppBar title [shown in picture 2].
The output in the YouTube course video:
My Output:
I have attached the entire code below, please help fix my mistake.
main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shopping_cart/cart_provider.dart';
import 'package:shopping_cart/cart_screen.dart';
import 'package:shopping_cart/product_list.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => CartProvider(),
child: Builder(builder: (BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(),
debugShowCheckedModeBanner: false,
home: const CartScreen(),
);
}),
);
}
}
product_list.dart
import 'package:badges/badges.dart';
import 'package:flutter/material.dart' hide Badge;
import 'package:provider/provider.dart';
import 'package:shopping_cart/cart_model.dart';
import 'package:shopping_cart/db_helper.dart';
import 'cart_provider.dart';
import 'cart_screen.dart';
class ProductListScreen extends StatefulWidget {
const ProductListScreen({super.key});
#override
State<ProductListScreen> createState() => _ProductListScreenState();
}
class _ProductListScreenState extends State<ProductListScreen> {
DBHelper? dbHelper = DBHelper();
List<String> productName = [
'Mango',
'Orange',
'Grapes',
'Banana',
'Chery',
'Peach',
'Mixed Fruit Basket'
];
List<String> productUnit = [
'KG',
'Dozen',
'KG',
'Dozen',
'KG',
'KG',
'KG',
];
List<int> productPrice = [10, 20, 30, 40, 50, 60, 70];
List<String> productImage = [
'https://image.shutterstock.com/image-photo/mango-isolated-on-white-background-600w-610892249.jpg',
'https://image.shutterstock.com/image-photo/orange-fruit-slices-leaves-isolated-600w-1386912362.jpg',
'https://image.shutterstock.com/image-photo/green-grape-leaves-isolated-on-600w-533487490.jpg',
'https://media.istockphoto.com/photos/banana-picture-id1184345169?s=612x612',
'https://media.istockphoto.com/photos/cherry-trio-with-stem-and-leaf-picture-id157428769?s=612x612',
'https://media.istockphoto.com/photos/single-whole-peach-fruit-with-leaf-and-slice-isolated-on-white-picture-id1151868959?s=612x612',
'https://media.istockphoto.com/photos/fruit-background-picture-id529664572?s=612x612',
];
#override
Widget build(BuildContext context) {
final cart = Provider.of<CartProvider>(context); // reference
return Scaffold(
appBar: AppBar(
title: const Text("Product List"),
centerTitle: true,
backgroundColor: Colors.deepPurple,
actions: [
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CartScreen(),
),
);
},
child: Center(
child: Badge(
badgeContent: Consumer<CartProvider>(
builder: (context, value, child) {
return Text(
value.getCounter().toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.bold,
),
);
},
),
badgeAnimation: const BadgeAnimation.fade(
animationDuration: Duration(milliseconds: 300),
),
child: const Icon(
Icons.shopping_cart_outlined,
size: 30,
),
),
),
),
const SizedBox(width: 20),
],
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: productName.length,
itemBuilder: ((context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
Image(
height: 100,
width: 100,
image:
NetworkImage(productImage[index].toString()),
),
const SizedBox(
width: 15,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
productName[index],
style: const TextStyle(fontSize: 23),
),
const SizedBox(
height: 5,
),
Text(
productUnit[index] +
" " r"$" +
productPrice[index].toString(),
style: const TextStyle(fontSize: 23),
),
const SizedBox(
height: 10,
),
Align(
alignment: Alignment.centerRight,
child: InkWell(
onTap: () {
dbHelper!
.insert(Cart(
id: index,
productId: index.toString(),
productName: productName[index]
.toString(),
initialPrice:
productPrice[index],
productPrice:
productPrice[index],
quantity: 1,
unitTag: productUnit[index]
.toString(),
image: productImage[index]
.toString()))
.then((value) {
print("Product is Added to Cart");
cart.addTotalPrice(double.parse(
productPrice[index].toString()));
cart.addCounter();
}).onError((error, stackTrace) {
print(error.toString());
});
},
child: Container(
height: 35,
width: 130,
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(50),
color: Colors.green,
),
child: const Center(
child: Text(
"Add to Cart",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500),
),
),
),
),
)
],
),
)
],
)
],
),
),
);
}),
),
),
Consumer<CartProvider>(builder: (context, value, child) {
return Column(
children: [
ReusableWidget(
'subtotal',
r'$' + value.getTotalPrice().toStringAsFixed(2),
),
],
);
})
],
),
);
}
}
class ReusableWidget extends StatelessWidget {
final String title, value;
const ReusableWidget(this.title, this.value, {super.key});
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
Text(
title,
style: Theme.of(context).textTheme.titleSmall,
),
Text(
value,
style: Theme.of(context).textTheme.titleSmall,
)
],
),
);
}
}
db_helper.dart
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
import 'dart:io' as io;
import 'cart_model.dart';
class DBHelper {
static Database? _db;
Future<Database?> get db async {
_db = await initDatabase();
if (_db != null) {
return _db!;
}
}
initDatabase() async {
io.Directory documentDirectory = await getApplicationDocumentsDirectory();
String path = join(documentDirectory.path, 'cart.db');
var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}
// Method
_onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE cart (id INTEGER PRIMARY KEY, productId VARCHAR UNIQUE, productName TEXT, initialPrice INTEGER, productPrice INTEGER, quantity INTEGER, unitTag TEXT, image TEXT)',
);
}
Future<Cart> insert(Cart cart) async {
print(cart.toMap());
var dbClient = await db;
await dbClient!.insert('cart', cart.toMap());
return cart;
}
Future<List<Cart>> getCartList() async {
var dbClient = await db;
final List<Map<String, Object?>> queryResult =
await dbClient!.query("cart");
return queryResult.map((e) => Cart.fromMap(e)).toList();
}
}
cart_screen.dart
import 'package:badges/badges.dart';
import 'package:flutter/material.dart' hide Badge;
import 'package:provider/provider.dart';
import 'cart_model.dart';
import 'cart_provider.dart';
class CartScreen extends StatefulWidget {
const CartScreen({super.key});
#override
State<CartScreen> createState() => _CartScreenState();
}
class _CartScreenState extends State<CartScreen> {
#override
Widget build(BuildContext context) {
final cart = Provider.of<CartProvider>(context);
return Scaffold(
appBar: AppBar(
title: const Text("My Products"),
centerTitle: true,
backgroundColor: Colors.deepPurple,
actions: [
Center(
child: Badge(
badgeContent: Consumer<CartProvider>(
builder: (context, value, child) {
return Text(
value.getCounter().toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.bold,
),
);
},
),
badgeAnimation: const BadgeAnimation.fade(
animationDuration: Duration(milliseconds: 300),
),
child: const Icon(
Icons.shopping_cart_outlined,
size: 30,
),
),
),
const SizedBox(width: 20),
],
),
body: Column(
children: [
FutureBuilder(
future: cart.getData(),
builder: (context, AsyncSnapshot<List<Cart>> snapshot) {
if (snapshot.hasData) {
return Expanded(
child: ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: ((context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
Image(
height: 100,
width: 100,
image: NetworkImage(
snapshot.data![index].image.toString(),
),
),
const SizedBox(
width: 15,
),
Expanded(
child: Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
snapshot.data![index].productName
.toString(),
),
const SizedBox(
height: 5,
),
Text(
snapshot.data![index].unitTag
.toString() +
" " r"$" +
snapshot.data![index].productPrice
.toString(),
style: const TextStyle(fontSize: 23),
),
const SizedBox(
height: 10,
),
Align(
alignment: Alignment.centerRight,
child: InkWell(
onTap: () {},
child: Container(
height: 35,
width: 130,
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(50),
color: Colors.green,
),
child: const Center(
child: Text(
"Add to Cart",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight:
FontWeight.w500),
),
),
),
),
)
],
),
)
],
)
],
),
),
);
}),
),
);
} else {
return const Text("Shahzain");
}
},
)
],
),
);
}
}
cart_provider.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shopping_cart/cart_model.dart';
import 'package:shopping_cart/db_helper.dart';
class CartProvider with ChangeNotifier {
DBHelper db = DBHelper(); // DBHelper() is a class
int _counter = 0;
int get counter => _counter;
double _totalPrice = 0.0;
double get totalPrice => _totalPrice;
late Future<List<Cart>> _cart;
Future<List<Cart>> get cart => _cart; // => means to indicate
Future<List<Cart>> getData() async {
_cart = db.getCartList();
return _cart;
}
void _setPrefItems() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('cart_item', _counter);
prefs.setDouble('total_price', _totalPrice);
notifyListeners();
}
void _getPrefItems() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
// giving initial value by ?? 0 for null safety
_counter = prefs.getInt('cart_item') ?? 0;
// giving initial value by ?? 0.0 for null safety
_totalPrice = prefs.getDouble('total_price') ?? 0.0;
notifyListeners();
}
void addTotalPrice(double productPrice) {
_totalPrice = _totalPrice + productPrice;
_setPrefItems();
notifyListeners();
}
void removeTotalPrice(double productPrice) {
_totalPrice = _totalPrice - productPrice;
_setPrefItems();
notifyListeners();
}
double getTotalPrice() {
_getPrefItems();
return _totalPrice;
}
void addCounter() {
// initial value of counter was 0, will be incremented to 1, and will be stored to sharedPreferences
_counter++;
_setPrefItems();
notifyListeners();
}
void removeCounter() {
_counter--;
_setPrefItems();
notifyListeners();
}
int getCounter() {
_getPrefItems();
return _counter;
}
}
cart_model.dart
class Cart {
late final int? id;
final String? productId;
final String? productName;
final int? initialPrice;
final int? productPrice;
final int? quantity;
final String? unitTag;
final String? image;
// Creating the constructor
Cart({
required this.id, // primary key
required this.productId,
required this.productName,
required this.initialPrice,
required this.productPrice,
required this.quantity,
required this.unitTag,
required this.image,
});
Cart.fromMap(Map<dynamic, dynamic> res) // res = resources
: id = res['id'],
productId = res['productId'],
productName = res['productName'],
initialPrice = res['initialPrice'],
productPrice = res['productPrice'],
quantity = res['quantity'],
unitTag = res['unitTag'],
image = res['image'];
Map<String, Object?> toMap(){
return {
'id' : id,
'productId' : productId,
'productName' : productName,
'initialPrice' : initialPrice,
'productPrice' : productPrice,
'quantity' : quantity,
'unitTag' : unitTag,
'image' : image
};
}
}
in your main.dart file
you set,
home: const CartScreen(),
and the video tutorial you have followed, he sets home: ProductListsScreen()
Fix this and I hope your problem will be solved,
also, be sure where to use const

rebuild my screen with future provider for specific widgets using id root

im trying to retrieve tasks from project in another words i want to rebuild my screen on viewing tasks with specific forgin key projectId i got this error while working on future provider
enter image description here
those are api/method/
enter image description here
enter image description here
enter image description here
here i want to view tasks only when i pass projectId
import 'package:flutter/material.dart';
import 'package:project/model/task_model.dart';
import 'package:project/project_dtetailForTest.dart';
import 'package:provider/provider.dart';
import 'new_project.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
class TaskById extends StatefulWidget {
//const TaskById({ Key? key }) : super(key: key);
final int project_id;
final Task task =Task();
TaskById({required this.project_id}):super();
#override
State<TaskById> createState() => _TaskByIdState();
}
class _TaskByIdState extends State<TaskById> {
#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: const Text(
'Project1',
style: 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: 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());
// }),
)
);
}
}
here how i pass projectId
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => TaskById(project_id: projectP.project[index].id!,)));
},
here the api , model,
// 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;
//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 TaskProvider with ChangeNotifier{
TaskProvider(){
this.fetchTask();
}
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();
}
}
Future fetchTask([project_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();
notifyListeners();
print('sucess view list');
return _task;
}
else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load tasks');
}
}
}
the error i got when i click on a project wiget to diplay its tasks on new screen
The following ProviderNotFoundException was thrown building Consumer<Task>(dirty):
Error: Could not find the correct Provider<Task> above this Consumer<Task> Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that Consumer<Task> is under your MultiProvider/Provider<Task>.
This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
child: Text(context.watch<Example>()),
),
}
consider using `builder` like so:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}

rest api flutter get method works while post doesnt

ihave this error from server response
this is the models and api
u can find full source code here https://github.com/alihassan75/project
// 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;
//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 Project {
Project({
this.id,
required this.project_name,
this.created_at,
// required this.start_date,
//required this.end_date,
required this.user,
});
int? id;
final String? project_name;
DateTime? created_at;
// final DateTime? start_date;
//final DateTime? end_date;
int user;
factory Project.fromJson(Map<String, dynamic> json) => Project(
id: json["id"],
project_name: json["project_name"],
created_at: DateTime.parse(json["created_at"]),
// start_date: DateTime.parse(json["start_date"]),
//end_date: DateTime.parse(json["end_date"]),
user: json["user"],
);
Map<String, dynamic> toJson() => {
"id": id,
"project_name": project_name,
"created_at": created_at?.toIso8601String(),
// "start_date": start_date?.toIso8601String(),
//"end_date": end_date?.toIso8601String(),
"user": user,
};
}
class ProjectProvider with ChangeNotifier{
ProjectProvider(){
this.fetchProject();
}
List<Project> _project = [];
List<Project> get project {
return [..._project];
}
void addProject(Project project) async {
final response = await http.post(Uri.parse('http://mostafahamed.pythonanywhere.com/project/api'),
headers: {"Content-Type": "application/json"}, body: json.encode(project));
if (response.statusCode == 201) {
project.id = json.decode(response.body)['id'];
_project.add(project);
notifyListeners();
print('sucess');
}
else {
print(response.body);
throw Exception('Failed to add project');
}
}
void deleteProject(Project project) async {
final response =
await http.delete(Uri.parse('http://mostafahamed.pythonanywhere.com/project/api${project.id}/'));
if (response.statusCode == 204) {
_project.remove(project);
notifyListeners();
print('sucess');
}
else {
throw Exception('Failed to load tasks');
}
}
fetchProject() async{
final response = await http
.get(Uri.parse('http://mostafahamed.pythonanywhere.com/project/api?format=json'));
if (response.statusCode==200){
var data = json.decode(response.body)as List;
_project=data.map<Project>((json) => Project.fromJson(json)).toList();
notifyListeners();
print('sucess');
}
else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load projects');
}
}
}
here i call back the post method with adding data function
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:project/model/project_model.dart';
//import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:project/model/user_Model.dart';
import 'home_page02.dart';
class NewProject extends StatefulWidget {
const NewProject({Key? key}) : super(key: key);
#override
State<NewProject> createState() => _NewProjectState();
}
class _NewProjectState extends State<NewProject> {
final TextEditingController projectname = TextEditingController();
//TextEditingController datelController = TextEditingController();
//DateTime _selectedDate = DateTime.now();
//DateTime currentDate = DateTime.now();
// Future<void> _selectDate(BuildContext context) async {
// final DateTime? pickedDate = await showDatePicker(
// context: context,
// initialDate: currentDate,
// firstDate: DateTime(2015),
// lastDate: DateTime(2050));
// if (pickedDate != null && pickedDate != currentDate)
// setState(() {
// currentDate = pickedDate;
// });
// else print('empty')
// ;}
void onAdd() {
//final DateTime? textVal = DateTime.parse(datelController.text);
final String desVal = projectname.text;
if (/*textVal != null&&*/ desVal.isNotEmpty) {
final Project project = Project(/*end_date: textVal,*/ project_name: desVal, user: 1, /*start_date: null,*/ );
Provider.of<ProjectProvider>(context, listen: false).addProject(project);
print('$desVal in sucess');
}
else{
print('empty or vaild');
//print('$textVal in vaild');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
// App Bar The upper part in the application
appBar: AppBar(
backgroundColor:const Color(0xff076792),
title: const Padding(
padding: EdgeInsets.only(
left: 50.0,
),
// project Name
child: Text(
'New Project',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 25.0,
shadows: [
Shadow(
color: Color(0xa6A2B6D4),
offset: Offset(7,5),
blurRadius:20),
]
),
),
),
iconTheme: const IconThemeData(
color:Colors.white,
size: 30.0,
),
),
body: SingleChildScrollView(
child: Column(
children: [
const Padding(
padding: EdgeInsets.only(
left: 10.0,
top: 30.0,
),
child: Padding(
padding: EdgeInsets.only(right: 80.0),
child: Text(
'Creating New Project',
style: TextStyle(
fontSize: 25.0,
color: Color(0xff076792),
fontWeight: FontWeight.bold,
),
),
),
),
Container(
margin: const EdgeInsets.fromLTRB(43, 24, 43, 15),
child: SizedBox(
height: 45,
child: TextField(
controller: projectname,
decoration: const InputDecoration(
hintText: "Enter project Name", //اليوسر يدخل اسم المشروع
hintStyle: TextStyle(
fontSize: 20,
color: Color(0xffc9c9c9), /*height: 2.5*/
),
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(width: 2, color: Color(0xFF09679a))),
),
keyboardType: TextInputType.name,
),
),
),
// Container(
// margin: const EdgeInsets.fromLTRB(43, 0, 43, 20),
// child: SizedBox(
// height: 45,
// child: TextField(
// controller: datelController,
// onTap: () {
// showDatePicker(
// context: context,
// initialDate: DateTime.now(),
// firstDate: DateTime.now(),
// lastDate: DateTime(2050),
// ).then((value) {
// datelController.text = DateFormat("yyyy-MM-dd").format(value!);
// });
// },
// decoration: const InputDecoration(
// hintText: "End Date",
// hintStyle: TextStyle(
// fontSize: 20,
// color: Color(0xffc9c9c9),
// ),
// enabledBorder: OutlineInputBorder(
// borderSide: BorderSide(width: 2, color: Color(0xFF09679a))),
// ),
// keyboardType: TextInputType.datetime,
// ),
// ),
// ),
const SizedBox(
height: 10.0,
),
Container(
width: double.infinity,
height: 54,
margin: const EdgeInsets.fromLTRB(75, 0, 75, 0),
child: ElevatedButton(
onPressed: () {
onAdd();
//_selectDate(context);
//Navigator.of(context).pop();
},
child: const Text(
'Create',
style: TextStyle(fontSize: 26, fontWeight: FontWeight.w400),
),
style: ElevatedButton.styleFrom(
primary: const Color(0xFF09679a),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
// f... flutter buttons!
side: const BorderSide(color: Colors.black, width: 1),
)),
),
),
Container(
alignment: Alignment.center,
child: const Padding(
padding: EdgeInsets.only(left: 60, top: 15.0, right: 60.0),
child: Text(
'By Creating This Project You Will Be Admin Of The Project',
style: TextStyle(
fontSize: 18.0,
fontStyle: FontStyle.italic,
color: Colors.black,
),
),
), //just text
),
// Text(currentDate.toString()),
// ElevatedButton(
// onPressed: () => _selectDate(context),
// child: Text('Select date'),
// ),
],
),
),
);
}
}
this app made to login users and view projects and add projects like todo app on the django server i can add project and view projects regstring with admin mail from python backend server .. in this app i can only view projects but cant add new project its my project for graduation so my life depends on this :D
full source code https://github.com/alihassan75/project
You are not getting the data "user" because you are not saving the "user" after login.
You need to save the user in any local storage. For, the demo purpose I will be saving that on HIVE
Import the hive package in pubspec.yaml
hive: ^2.1.0
In the main function(before run app) initialize and open a box "user"
await Hive.initFlutter();
await Hive.openBox('User');
You can push to user box in login function like this.
box = Hive.box('User');
int userId = responseJson['user']['id'];
box.put('user_id', userId);
You can read the user when ever you want like this.
late Box box;
late int userid;
box = Hive.box('User');
super.initState();
final data = box.get('user_id');
Now you can pass the data to the http api call.
Thank you

flutter future builder keeps loading one-to-many relationship

im tring to view tasks on alone screen from data using rest api dart django
with project_id its one-to-many relationship project has many tasks so i want to dispay the tasks when i click on project widget using future builder
Edit :i found the problem check my answer below
here is usage of future builder and task list
import 'package:flutter/material.dart';
import 'package:project/model/task_model.dart';
import 'package:project/project_dtetailForTest.dart';
import 'package:provider/provider.dart';
import 'new_project.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
class TaskById extends StatefulWidget {
//const TaskById({ Key? key }) : super(key: key);
final int project_id;
//final Task task =Task();
TaskById({required this.project_id}):super();
#override
State<TaskById> createState() => _TaskByIdState();
}
class _TaskByIdState extends State<TaskById> {
#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: const Text(
'Project1',
style: 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: FutureBuilder(
future: TaskProvider().fetchTask(widget.project_id),
builder: (context, snapshot){
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData && snapshot is List<Task>
?TaskList(task:snapshot.data as List<Task>)
: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;
TaskList({Key? key, required this.task}) : super(key: key);
#override
Widget build(BuildContext context) {
final taskP= Provider.of<TaskProvider>(context );
// TODO: implement build
return 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,
)),
],
),
]),
),),
),
);
}),
)
],
);
}
}
here the api and model of task
// 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;
//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 TaskProvider with ChangeNotifier{
TaskProvider(){
this.fetchTask();
}
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();
}
}
Future<List<Task>> fetchTask([project_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();
notifyListeners();
print('sucess view task list');
print(response.body);
return _task;
}
else {
print(response.body);
print(response.statusCode);
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load tasks');
}
}
}
when i click on project wiget the screen keeps loading
I removed a condition && snapshot is List from future builder
and it works perfectly but
make sure to prevent the use of future builder if you have changeable values as future builder fetch data once I'm right now working to convert future builder into stream builder
if u have the same problem make sure all the types are the same
good luck to you all : )

flutter error type 'Null' is not a subtype of type 'String'

so i want to print user name and user username in the profile page and in the end it shows it but for a few seconds there is a red screen that says The following _TypeError was thrown building Profile_page(dirty, state: _Profile_pageState#68414):
type 'Null' is not a subtype of type 'String'
this is the code of main.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/name.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question1.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question2.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question3.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question4.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question5.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/photo.dart';
import 'package:gp1_7_2022/screen/home/Profile_Page.dart';
import 'package:firebase_core/firebase_core.dart';
/*pages */
import 'package:gp1_7_2022/screen/auth/signup_login.dart';
import 'package:gp1_7_2022/screen/auth/signup/userAuth/signup.dart';
import 'package:gp1_7_2022/screen/auth/Login/login.dart';
import 'package:gp1_7_2022/screen/auth/signup/userAuth/signupConfirmationCode.dart';
import 'package:gp1_7_2022/screen/auth/signup/userAuth/signupPassword.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/signupBirthday.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/signupUsername.dart';
import 'package:gp1_7_2022/screen/auth/Login/forget_password.dart';
import 'package:gp1_7_2022/screen/settings.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MaterialApp(
initialRoute: "/",
routes: {
"/": (context) => MainPage(),
"/signup": (context)=> Signup(),
'/login':(context)=>Login(),
'/Profile_Page':(context) => Profile_page(uid: FirebaseAuth.instance.currentUser!.uid),
// '/confirmationCode':(context) => ConfirmationCode(),
// '/signupPassword':(context) => signupPassword(),
'/signupBirthday':(context) => SignupBirthday(),
'/signupUsername':(context) => SignupUsername(),
'/forget_password':(context) => forget_password(),
'/name':(context) => name(),
'/question1':(context) => question1(),
'/question2':(context) => question2(),
'/question3':(context) => question3(),
'/question4':(context) => question4(),
'/question5':(context) => question5(),
'/photo':(context) => Photo(),
'/settings':(context) => settings(),
}
)
);
}
class MainPage extends StatelessWidget {
const MainPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot){
if(snapshot.connectionState==ConnectionState.waiting){
return const Center(child: CircularProgressIndicator());
}else if(snapshot.hasError){
return const Center(child: Text("Something went wrong!"));
}else if(snapshot.hasData){
if(FirebaseAuth.instance.currentUser!.emailVerified && FirebaseAuth.instance.currentUser!.uid != null ){
String uid = FirebaseAuth.instance.currentUser!.uid;
return Profile_page(uid: uid );
}else{
String? x = FirebaseAuth.instance.currentUser!.email;
String y= x??" ";
return ConfirmationCode(email: y);
}
} else{
return const Signup_Login();
}
},
),
);
}
}
this is the code of profile_page.dart
// import 'dart:html';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:focused_menu/focused_menu.dart';
import 'package:focused_menu/modals.dart';
/*pages */
/*colors */
import 'package:gp1_7_2022/config/palette.dart';
import 'package:gp1_7_2022/Widgets/follow_button.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:gp1_7_2022/screen/settings.dart';
class Profile_page extends StatefulWidget {
final uid;
const Profile_page({Key? key, required this.uid}) : super(key: key);
#override
State<Profile_page> createState() => _Profile_pageState();
}
class _Profile_pageState extends State<Profile_page> {
var padding= 0.8;
var userData = {};
#override
void initState() {
super.initState();
getData();
}
/* get data method */
getData() async {
try {
if (widget.uid != null) {
var userSnap = await FirebaseFirestore.instance.collection('users').doc(
widget.uid).get();
userData = userSnap.data()!;
setState(() {
});
}
}
catch(e){
Alert(
context: context,
title: "Something went wrong!",
desc: e.toString(),
).show();
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Palette.backgroundColor,
appBar: AppBar(
//appBar style
elevation: 0,
backgroundColor: Palette.backgroundColor,
automaticallyImplyLeading: false,//no arrow
//username
title: Padding(
padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
child: Text(
userData['username'],
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 24,
),
),
),
//setting icon
actions:[
FocusedMenuHolder(
//
menuWidth: MediaQuery.of(context).size.width * 0.4,
menuOffset: 0,
menuItemExtent: 49,
//list
menuItems: [
FocusedMenuItem(
title: const Text("Log out"),
trailingIcon: const Icon(Icons.logout),
onPressed: (){
/*go to sign up page*/
Navigator.pushNamed(context, '/');
return FirebaseAuth.instance.signOut();
}
),
FocusedMenuItem(
title: const Text("Settings"),
trailingIcon: const Icon(Icons.settings),
onPressed: (){
Navigator.of(context).popAndPushNamed('/settings');
},
),
],
openWithTap: true,
onPressed: (){},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Image.asset(
"assets/menu-icon.png",
height: 25,
width: 25,
),
),
),
],
),
body: ListView(
children: [
Container(
margin: const EdgeInsets.all(16),
child: Column(
children: [
Row(
children: [
//user photo
const Padding(
padding: EdgeInsets.fromLTRB(0, 0, 40, 0),
child: CircleAvatar(
backgroundColor: Colors.white ,
child: Icon(
Icons.account_circle_sharp,
color: Colors.grey,
size: 90,
),
),
),
//end user photo
Expanded(
flex: 7,
child: Column(
children: [
SizedBox(height:40,),
//post, followers and following
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
buildStatColumn(20, "posts"),
buildStatColumn(150, "Followers"),
buildStatColumn(10, "Following"),
],
),
//end post, followers and following
],
),
),
],
),
//username
Container(
alignment: Alignment.centerLeft,
padding: EdgeInsets.fromLTRB(10, 40, 0, 0),
child: Text(
userData['name'],
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
),
//end of username
//bio
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.fromLTRB(10, 1, 0, 0),
child: const Text(
'bio',
style: TextStyle(
fontSize: 16,
),
),
),
//end of bio
//edit profile button
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
FollowButton(
text: 'Edit profile',
backgroundColor: Palette.backgroundColor,
borderColor: Palette.grey,
textColor: Colors.black,
function: () {},
)
],
),
//end of button
],
),
),
],
),
);
}
}
// function to show following/followers/# of posts
Column buildStatColumn(int num, String label) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
num.toString(),
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
Container(
margin: const EdgeInsets.only(top: 4),
child: Text(
label,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400,
color: Colors.grey,
),
),
),
],
);
}
enter image description here
Show some other widgets until data is not fully loaded.
class _Profile_pageState extends State<Profile_page> {
...
bool _isloaded = false; // Add this boolean
In getData function
getData() async {
try {
...
setState(() {
_isloaded = true; // when data is loaded update state
});
}
...
In build, return widget according to data(user)
#override
Widget build(BuildContext context) {
return _isloaded == false ?
Center(
child: CircularProgressIndicator(), // Show indicator
)
: Scaffold(
backgroundColor: Palette.backgroundColor,
...
); //Scaffold
You're assuring flutter that the data isn't null which will result in a momentary error. You can try either setting a load bool that sets to true when the data arrives or using the ?? operator. e.g userData['name'] ?? "loading" which will print loading incase the userData['name'] is null

Categories

Resources