Bottom Overflowed By Infinity Pixels Flutter (Dart) - flutter

I added an Navigation bar to the bottom of the app and discovered the error. I tried wrapping a bunch of widgets with scroll view mainaxisalignment, expanded and tried different methods that i saw on youtube or on Stack Overflow Overflowed by Infinity Pixels
The code for the Home page and navigation bar:
import 'package:date_picker_timeline/date_picker_timeline.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:ride/controllers/task_controller.dart';
import 'package:ride/services/theme_services.dart';
import 'package:ride/ui/add_task_bar.dart';
import 'package:ride/ui/theme.dart';
import 'package:ride/ui/widgets/button.dart';
import 'package:ride/ui/widgets/task_tile.dart';
import '../models/task.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final int _selectedIndex = 0;
static const List<Widget> _widgetOptions = <Widget>[
AddTaskPage(),
];
DateTime _selectedDate = DateTime.now();
final _taskController = Get.put(TaskController());
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appbar(),
backgroundColor: context.theme.colorScheme.background,
body:
Column(children: [
_addTaskBar(),
_addDateBar(),
_widgetOptions.elementAt(_selectedIndex),
_showTasks(),
]),
);
}
_showTasks() {
return Expanded(
child: Obx(() {
return ListView.builder(
itemCount: _taskController.taskList.length,
itemBuilder: (_, index) {
Task task = _taskController.taskList[index];
//print(task.toJson());
if (task.date == DateFormat.yMd().format(_selectedDate)) {
return AnimationConfiguration.staggeredList(
position: index,
child: SlideAnimation(
child: FadeInAnimation(
child: Row(
children: [
GestureDetector(
onTap: () {
_showBottomSheet(context, task);
},
child: TaskTile(task),
)
],
))));
} else {
return Container();
}
});
}),
);
}
_showBottomSheet(BuildContext context, Task task) {
Get.bottomSheet(
Container(
padding: const EdgeInsets.only(top: 4),
height: task.isCompleted == 1
? MediaQuery.of(context).size.height * 0.24
: MediaQuery.of(context).size.height * 0.32,
color: Get.isDarkMode ? Colors.grey[850] : Colors.white,
child: Column(children: [
Container(
height: 6,
width: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.grey[600]),
),
const Spacer(),
task.isCompleted == 1
? Container()
: _bottomSheetButton(
label: "Join",
onTap: () {
_taskController.markTaskCompleted(task.id!);
Get.back();
},
clr: primaryClr,
context: context),
_bottomSheetButton(
label: "Delete",
onTap: () {
_taskController.delete(task);
Get.back();
},
clr: Colors.red[400]!,
context: context),
const SizedBox(
height: 20,
),
_bottomSheetButton(
label: "Close",
onTap: () {
Get.back();
},
clr: Colors.red[400]!,
isClose: true,
context: context),
const SizedBox(height: 10),
]),
),
);
}
_bottomSheetButton({
required String label,
required Function()? onTap,
required Color clr,
bool isClose = false,
required BuildContext context,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4),
height: 55,
width: MediaQuery.of(context).size.width * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: isClose == true
? Get.isDarkMode
? Colors.grey[600]!
: Colors.grey[400]!
: clr),
borderRadius: BorderRadius.circular(20),
color: isClose == true ? Colors.transparent : clr,
),
child: Center(
child: Text(
label,
style:
isClose ? titleStyle : titleStyle.copyWith(color: Colors.white),
)),
),
);
}
_addDateBar() {
return Container(
margin: const EdgeInsets.only(
top: 20,
left: 20,
),
child: DatePicker(
DateTime.now(),
height: 100,
width: 80,
initialSelectedDate: DateTime.now(),
selectionColor: primaryClr,
selectedTextColor: Colors.white,
dateTextStyle: GoogleFonts.lato(
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.w600, color: Colors.grey),
),
dayTextStyle: GoogleFonts.lato(
textStyle: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey),
),
monthTextStyle: GoogleFonts.lato(
textStyle: const TextStyle(
fontSize: 14, fontWeight: FontWeight.w600, color: Colors.grey),
),
onDateChange: (date) {
setState(() {
_selectedDate = date;
});
},
),
);
}
_addTaskBar() {
return Container(
margin: const EdgeInsets.only(right: 20, top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
DateFormat.yMMMMd().format(DateTime.now()),
style: subHeadingStyle,
),
Text(
'Today',
style: headingStyle,
)
],
),
),
MyButton(
label: "+ Add",
onTap: () async {
await Get.to(const AddTaskPage());
_taskController.getTasks();
})
],
),
);
}
_appbar() {
return AppBar(
elevation: 0,
backgroundColor: context.theme.colorScheme.background,
leading: GestureDetector(
onTap: () {
ThemeService().switchTheme();
},
child: Icon(
Get.isDarkMode
? Icons.wb_sunny_outlined
: Icons.dark_mode_outlined,
size: 30,
color: Get.isDarkMode ? Colors.white : Colors.black),
),
actions: [
Icon(Icons.person_outline,
size: 30, color: Get.isDarkMode ? Colors.white : Colors.black),
const SizedBox(
width: 15,
)
]);
}
}
main.dart:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:ride/login/login.dart';
import 'package:ride/services/theme_services.dart';
import 'package:ride/ui/home_page.dart';
import 'package:ride/ui/theme.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
final isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
await Firebase.initializeApp();
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp(isLoggedIn: isLoggedIn));
}
class MyApp extends StatelessWidget {
final bool isLoggedIn;
const MyApp({super.key, required this.isLoggedIn});
//Root of Application
#override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: Themes.light,
darkTheme: Themes.dark,
themeMode: ThemeService().theme,
home: isLoggedIn ? const HomePage() : LogIn());
}
}
I tried Wrapping the Container and SafeArea widgets in the Expanded widget and tried wrapping the same widgets with SingleChildScrollView AND wrapped the 2 widgets with Expanded AND SingleChildScrollView but nothing worked.

I fixed it!! I removed _widgetOptions.elementAt(_selectedIndex) and all errors are gone.

Related

The problem happens in the ListView.builder which the card can't clip at the top

The problem happens in the ListView.builder which the card can't clip at the top.Is my code have anything missing? How can I do?
The problem happens in the ListView.builder which the card can't clip at the top. Is my code have anything missing? How can I do?
The problem happens in the ListView.builder which the card can't clip at the top. Is my code have anything missing? How can I do?
There are a space between the card and with the top
[1]: https://i.stack.imgur.com/fpJ4h.png
This is what I want and expected
[2]: https://i.stack.imgur.com/aAhmh.png
This is the AllProduct.dart
import 'package:flutter/material.dart';
import 'package:penang_beachess/blog_page/blog_page.dart';
import 'package:penang_beachess/provider/favorite_list.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:penang_beachess/widget/background-image.dart';
import 'package:provider/provider.dart';
import '../widget/background.dart';
class AllBlog extends StatefulWidget {
const AllBlog({Key? key}) : super(key: key);
#override
State<AllBlog> createState() => _AllBlogState();
}
class _AllBlogState extends State<AllBlog> {
bool _isBookmarked(Beach newAddBeach) {
List favoritedBeach = favoriteBeachList;
if (favoritedBeach.contains(newAddBeach)) {
return true;
}
return false;
}
#override
Widget build(BuildContext context) {
var favoriteList = Provider.of<favoriteProvider>(context);
return Stack(
children: [
//problem Here
ListView.builder(
itemCount: beachList.length,
itemBuilder: (context, index) {
Beach beach = beachList[index];
int currentIndex = index;
return Card(
child: ListTile(
title: Text(beach.title,
style: GoogleFonts.permanentMarker(
textStyle: TextStyle(fontSize: 15),
)),
subtitle: Row(
children: [
const Icon(
Icons.location_on,
size: 16.0,
),
Text(
beach.location,
style: GoogleFonts.permanentMarker(
textStyle: TextStyle(fontSize: 12.0),
),
overflow: TextOverflow.ellipsis,
),
],
),
leading: SizedBox(
height: 80,
width: 80,
child: Image.asset(beach.urlToImage1),
),
// add bookmark here
trailing: IconButton(
onPressed: () {
if (!_isBookmarked(beach)) {
setState(() {
favoriteBeachList.add(beachList[currentIndex]);
});
} else {
setState(() {
favoriteBeachList.remove(beachList[currentIndex]);
});
}
Beach _beach = Beach(
title: beachList[index].title,
location: beachList[index].location,
source: beachList[index].source,
author: beachList[index].author,
description: beachList[index].description,
urlToImage1: beachList[index].urlToImage1,
urlToImage2: beachList[index].urlToImage2,
facilities: beachList[index].facilities,
urlToImage3: beachList[index].urlToImage3,
status: beachList[index].status,
likeCount: beachList[index].likeCount,
);
if (_beach.status == 'false') {
setState(() {
beachList[index].status = 'true';
});
favoriteList.addToList(_beach);
} else if (_beach.status == 'true') {
setState(() {
beachList[index].status = 'false';
});
favoriteList.removeFromList(_beach);
}
},
icon: Icon(_isBookmarked(beach)
? Icons.bookmark
: Icons.bookmark_border),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BlogPage(beach)));
}),
);
}),
],
);
}
}
This is Home.dart
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:two_life/model/product.dart';
import 'package:two_life/model/provider.dart/favorite_list.dart';
import 'package:two_life/screens/ReProductDetail.dart/Re3.dart';
import 'package:two_life/screens/allproduct.dart';
import 'package:two_life/screens/homepagecard.dart';
import 'package:two_life/screens/productDetails.dart';
import 'ReProductDetail.dart/Re1.dart';
import 'ReProductDetail.dart/Re2.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Color.fromRGBO(211, 211, 211, 1),
child: Align(
alignment: Alignment.center,
child: Column(
children: [
SizedBox(
height: 70,
),
Container(
width: 350,
height: 100,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(30),
),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Text(
"Welcome to 2.LIFE!\n\n Enjoy your shopping with us via 2.LIFE!!",
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 17)),
),
),
SizedBox(
height: 15,
),
Container(
width: 350,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Text("Recommended",
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 17)),
),
),
Container(
child: listview(),
),
Container(
width: 350,
height: 30,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Text("All Product",
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 17)),
),
),
// Here is the SizedBox for the AllProduct in AllProduct.dart
SizedBox(
height: 280,
child: AllProduct(),
),
],
),
),
));
}
}
class listview extends StatefulWidget {
const listview({super.key});
#override
State<listview> createState() => _listviewState();
}
class _listviewState extends State<listview> {
#override
Widget build(BuildContext context) {
return Container(
height: 200,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
//Product 1
Padding(
......

Flutter: Making a Dropdown Multiselect with Checkboxes

am building a flutter app and am am working with a data from a API i got the list and evreything i did a search bar that works properly by typing either the number of the ticket or the description but am trying to add a new filter , a checkbox that filters the data i have 2 problems
1: when i press on a checkbox and type confirm it works and it shows but the checkbox dosent stay checked
2: how can i implement it so it filter the data from the api directly
and thank you
// ignore_for_file: use_key_in_widget_constructors, avoid_print, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, prefer_const_constructors, non_constant_identifier_names, unnecessary_new, avoid_function_literals_in_foreach_calls, unused_import, avoid_types_as_parameter_names, unused_label, unused_element, file_names, library_private_types_in_public_api, unnecessary_string_interpolations
import 'dart:convert';
import 'dart:io';
import 'package:az/Actifs.dart';
import 'package:az/SR_Details.dart';
import 'package:az/main.dart';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'class/sr.dart';
import 'package:dropdown_search/dropdown_search.dart';
class DataFromAPI extends StatefulWidget {
#override
_DataFromAPIState createState() => _DataFromAPIState();
}
List<Sr> _MyAllData=[];
List<Sr> _SrForDsiplay=[];
Map<String, Color> map={
"QUEUED":Color.fromARGB(255, 255, 136, 0),
"CLOSED":Colors.grey,
"Rejected":Colors.red,
"INPROG":Colors.green,
"PENDING":Colors.blue,
"RESOLVED":Colors.green,
"NEW":Colors.blue,
};
Map<String, String> map1={
"1":"Urgent",
"2":"High",
"3":"Medium",
"4":"Low",
};
/*Map<String, Color> map3={
"Urgent":Colors.red,
"High":Color.fromARGB(255, 255, 139, 131),
"Medium":Colors.blue,
"Low":Colors.green,
"null":Colors.grey,
};*/
class Multiselect extends StatefulWidget {
final List<String> items;
const Multiselect({Key? key, required this.items}) : super(key: key);
#override
State<Multiselect> createState() => _MultiselectState();
}
class _MultiselectState extends State<Multiselect> {
final List<String> _selectedItems=[];
void _itemChange(String itemValue, bool isSelected) {
setState(() {
if (isSelected) {
_selectedItems.add(itemValue);
} else {
_selectedItems.remove(itemValue);
}
});
}
// this function is called when the Cancel button is pressed
void _cancel() {
Navigator.pop(context);
}
// this function is called when the Submit button is tapped
void _submit() {
Navigator.pop(context, _selectedItems);
}
#override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Select Topics'),
content: SingleChildScrollView(
child: ListBody(
children: widget.items
.map((item) => CheckboxListTile(
value: _selectedItems.contains(item),
title: Text(item),
controlAffinity: ListTileControlAffinity.leading,
onChanged: (isChecked) => _itemChange(item, isChecked!),
))
.toList(),
),
),
actions: [
TextButton(
onPressed: _cancel,
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: _submit,
child: const Text('Submit'),
),
],
);
}
}
class _DataFromAPIState extends State<DataFromAPI> {
List<String> _selectedItems=[];
String title_string = "Liste des SR :";
void _ShowMultiSelect() async{
final List<String> items=[
'QUEUED',
'CLOSED',
'Rejected',
'INPROG',
'PENDING',
'RESOLVED',
'NEW',
];
final List<String>? results =await showDialog(
context: context,
builder: (BuildContext context) {
return Multiselect(items: items);
},
);
if(results !=null){
setState(() {
_selectedItems=results;
});
}
}
#override
void initState() {
loadData().then((value) {
_MyAllData.clear();
setState(() {
_MyAllData.addAll(value);
_SrForDsiplay=_MyAllData;
});
});
super.initState();
}
Future<List<Sr>> loadData() async {
try {
var response = await http.get(Uri.parse(
'http:MXSR/?_lid=&_lpwd=&_format=json'));
if (response.statusCode == 200) {
final jsonBody = json.decode(response.body);
Demandes data = Demandes.fromJson(jsonBody);
final srAttributes = data.queryMxsrResponse.mxsrSet.sr;
title_string='Liste des SR : ${srAttributes.length.toString()}';
return srAttributes;
}
} catch (e) {
throw Exception(e.toString());
}
throw Exception("");
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner:false,
home: new Scaffold(resizeToAvoidBottomInset: false ,
appBar: AppBar(
title: Text(title_string),
leading: IconButton(
icon: Icon(Icons.arrow_back), onPressed: () { Navigator.push(
context, MaterialPageRoute(builder: (context) => Home())); },
),
flexibleSpace: InkWell(onTap: () {
},),
),
body: FutureBuilder<List<Sr>?>(
future: loadData(),
builder: (context, snapshot) {
if (_MyAllData.isEmpty) {
return SizedBox(
height: MediaQuery.of(context).size.height / 1.3,
child: Center(
child: CircularProgressIndicator(),
),
);
} else { return
ListView(
children: <Widget>[Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children:<Widget>[ElevatedButton(onPressed: _ShowMultiSelect,
child: const Text('Filter')),
const Divider(
height: 30,
),
Wrap(
children: _selectedItems
.map((e) => Chip(
label: Text(e),
))
.toList(),
),
Row(children:<Widget>[ Expanded(
child: TextField(
decoration:
InputDecoration( hintText: "Enter id or description"),
onChanged: (text) {
text=text.toLowerCase();
setState(() {
_SrForDsiplay =_MyAllData.where((srAttributes) {
var srDescription = srAttributes.attributes.description!.content.toString().toLowerCase();
var srID= srAttributes.attributes.ticketid.content.toString();
return srDescription.contains(text) || srID.contains(text);
}).toList();
title_string='Liste des SR : ${_SrForDsiplay.length.toString()}';
print(title_string);
}
);
},
)),])
],
),),
new ListView.builder(scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _SrForDsiplay.length,
itemBuilder: ((_, index) {
return
new ListTile(
title: new Card(
margin: new EdgeInsets.symmetric(
vertical: 2.0, horizontal: 8.0),
elevation: 10,
child: new ListTile(
title: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(padding: new EdgeInsets.all(2.0)),
Row(children :[
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color: map['${_SrForDsiplay[index].attributes.status.content}'],
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text(' ${_SrForDsiplay[index].attributes.status.content} '),
),
Container(child: Text(' '),),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color:Colors.grey,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text( map1['${_SrForDsiplay[index].attributes.reportedpriority?.content}'] ?? " null "),
),
],
),
SizedBox(
height: 8,
),
Row(children: <Widget>[
Expanded( child: Container(child: Text('${_SrForDsiplay[index].attributes.description?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600)),),),),
Expanded(child: Container(child:Text( ' ${_SrForDsiplay[index].attributes.ticketid.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400)),)))
],),
new Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Text(
'Reported : ${DateFormat.yMMMMEEEEd().format(DateTime.parse('${_SrForDsiplay[index].attributes.statusdate.content}' ))}' ,
style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
new Text(
'Reported by : ${_SrForDsiplay[index].attributes.reportedby?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
Row(children: [new Image(image: AssetImage('assets/courroi.png'), width: 20),
Text(
'${_SrForDsiplay[index].relatedMbos?.asset[0].attributes.descriptionasset?.content}'),], ),
Row(children: [new Image(image: AssetImage('assets/emp.png'), width: 20),
Text(
'${_SrForDsiplay[index].attributes.assetsiteid?.content}'),], ) ,
Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Row(children:[
Expanded(child: Badge(
position: BadgePosition.topEnd(top: -8, end: 20),
badgeColor: Colors.grey,
badgeContent: Text('1'),
child :IconButton(icon :Icon(Icons.file_present_rounded), padding: const EdgeInsets.all(0),
onPressed: () {
},
),
)
),
Expanded(child: IconButton (
icon: Icon(Icons.file_copy),
onPressed: () { },
),),
Expanded(child: IconButton(onPressed:() {
}, icon: Icon(Icons.delete)) )
],)
],
),
trailing: Icon(Icons.arrow_forward_ios_rounded),
),
),
onTap: () {
Navigator.push(
context,MaterialPageRoute(builder: (context) =>SrDetailsScreen(sr: _SrForDsiplay[index])),
);
}
);
}
),
)
]
);
}
},
),
),
);
}
}

Flutter list is not rebuilt and the new item has not appeared

hi i m using the rest API to bring data from the data base and when i make a change in the data base i want it so if i Go to the other screen and Pop to the previous screen i want the get request from the api to re build the list and the new items should appear but at the moment it dosen't refresh so only the old list appears any help and thank you
import 'dart:convert';
import 'dart:io';
import 'package:az/Actifs.dart';
import 'package:az/SR_Details.dart';
import 'package:az/main.dart';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'class/sr.dart';
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DataFromAPI(),
);
}
}
class DataFromAPI extends StatefulWidget {
#override
_DataFromAPIState createState() => _DataFromAPIState();
}
List<Sr> _MyAllData=[];
List<Sr> _SrForDsiplay=[];
Map<String, Color> map={
"QUEUED":Color.fromARGB(255, 255, 136, 0),
"CLOSED":Colors.grey,
"Rejeced":Colors.red,
"INPROG":Colors.green,
"PENDING":Colors.blue,
"RESOLVED":Colors.green,
"NEW":Colors.blue,
};
Map<String, String> map1={
"1":"Urgent",
"2":"High",
"3":"Medium",
"4":"Low",
};
Map<String, Color> map3={
"Urgent":Colors.red,
"High":Color.fromARGB(255, 255, 139, 131),
"Medium":Colors.blue,
"Low":Colors.green,
"null":Colors.grey,
};
class _DataFromAPIState extends State<DataFromAPI> {
String title_string = "Liste des SR";
#override
void initState() {
loadData().then((value) {
setState(() {
_MyAllData.addAll(value);
_SrForDsiplay=_MyAllData;
});
});
super.initState();
}
Future<List<Sr>> loadData() async {
try {
var response = await http.get(Uri.parse(
'http://192.168.1.59:9080/maxrest/rest/mbo/sr/?_lid=maxadmin&_lpwd=maxadmin&_format=json'));
if (response.statusCode == 200) {
final jsonBody = json.decode(response.body);
Demandes data = Demandes.fromJson(jsonBody);
final srAttributes = data.srMboSet.sr;
title_string='Liste des SR : ${srAttributes.length.toString()}';
return srAttributes;
}
} catch (e) {
throw Exception(e.toString());
}
throw Exception("");
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner:false,
home: new Scaffold(resizeToAvoidBottomInset: false ,
appBar: AppBar(
title: Text(title_string),
leading: IconButton(
icon: Icon(Icons.arrow_back), onPressed: () { Navigator.push(
context, MaterialPageRoute(builder: (context) => Home())); },
),
),
body: FutureBuilder<List<Sr>?>(
future: loadData(),
builder: (context, snapshot) {
if (!(_MyAllData.isNotEmpty)) {
return SizedBox(
height: MediaQuery.of(context).size.height / 1.3,
child: Center(
child: CircularProgressIndicator(),
),
);
} else { return ListView(
children: <Widget>[Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
decoration:
InputDecoration(icon: Icon(Icons.search), hintText: "Enter id or description"),
onChanged: (text) {
text=text.toLowerCase();
setState(() {
_SrForDsiplay =_MyAllData.where((srAttributes) {
var srDescription = srAttributes.attributes.description!.content.toString().toLowerCase();
var srID= srAttributes.attributes.ticketid.content.toString();
return srDescription.contains(text) || srID.contains(text);
}).toList();
title_string='Liste des SR : ${_SrForDsiplay.length.toString()}';
print(title_string);
}
);
},
),
),
new ListView.builder(scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _SrForDsiplay.length,
itemBuilder: ((_, index) {
return
new ListTile(
title: new Card(
margin: new EdgeInsets.symmetric(
vertical: 2.0, horizontal: 8.0),
elevation: 10,
child: new ListTile(
title: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(padding: new EdgeInsets.all(2.0)),
Row(children :[
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color: map['${_SrForDsiplay[index].attributes.status.content}'],
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text(' ${_SrForDsiplay[index].attributes.status.content} '),
),
Container(child: Text(' '),),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color: map3[map1['${_SrForDsiplay[index].attributes.reportedpriority?.content}']],
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text( map1['${_SrForDsiplay[index].attributes.reportedpriority?.content}'] ?? " null "),
),
],
),
SizedBox(
height: 8,
),
Row(children: <Widget>[
Expanded( child: Container(child: Text('${_SrForDsiplay[index].attributes.description?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600)),),),),
Expanded(child: Container(child:Text( ' ${_SrForDsiplay[index].attributes.ticketid.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400)),)))
],),
new Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Text(
'Reported : ${DateFormat.yMMMMEEEEd().format(DateTime.parse('${_SrForDsiplay[index].attributes.statusdate.content}' ))}' ,
style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
new Text(
'Reported by : ${_SrForDsiplay[index].attributes.reportedby?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
Row(children: [new Image(image: AssetImage('assets/courroi.png'), width: 20),
Text(
'${_SrForDsiplay[index].attributes.assetnum?.content}'),], ),
Row(children: [new Image(image: AssetImage('assets/emp.png'), width: 20),
Text(
'${_SrForDsiplay[index].attributes.assetsiteid?.content}'),], ) ,
Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Row(children:[
Expanded(child: Badge(
position: BadgePosition.topEnd(top: -8, end: 20),
badgeColor: Colors.grey,
badgeContent: Text('1'),
child :IconButton(icon :Icon(Icons.file_present_rounded), padding: const EdgeInsets.all(0),
onPressed: () {
},),
)
),
Expanded(child: IconButton (
icon: Icon(Icons.file_copy),
onPressed: () { },
),),
Expanded(child: IconButton(onPressed:() {
}, icon: Icon(Icons.delete)) )
],)
],
),
trailing: Icon(Icons.arrow_forward_ios_rounded),
),
),
onTap: () {
/* Navigator.push(
context,MaterialPageRoute(builder: (context) =>SRDetail()),
);*/
}
);
}
),
)
]
);
}
},
),
),
);
}
}```
By the way, this is not good to call loadData() function in initState and Future.builder() at the same time.
Moreover, the common usage of Future is to handle HTTP calls. What you can listen to on a Future is its state. Whether it's done, finished with success, or had an error. But that's it.
A Future can't listen to a variable change. It's a one-time response. Instead, you'll need to use a Stream.

'package:flutter/src/widgets/framework.dart':failed

#main.dart file
import 'package:flutter/material.dart';
import './widgets/new_transaction.dart';
import './widgets/transaction_list.dart';
import './widgets/chart.dart';
import './models/tranasction.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Personal Expenses',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.amber,
// errorColor: Colors.red,
fontFamily: 'Quicksand',
textTheme: ThemeData.light().textTheme.copyWith(
titleMedium: TextStyle(
fontFamily: 'OpenSans',
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
appBarTheme: AppBarTheme(
textTheme: ThemeData.light().textTheme.copyWith(
titleMedium: TextStyle(
fontFamily: 'OpenSans',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
)),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
// String titleInput;
// String amountInput;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<Transaction> _userTransactions = [
// Transaction(
// id: 't1',
// title: 'New Shoes',
// amount: 69.99,
// date: DateTime.now(),
// ),
// Transaction(
// id: 't2',
// title: 'Weekly Groceries',
// amount: 16.53,
// date: DateTime.now(),
// ),
];
List<Transaction> get _recentTransactions {
return _userTransactions.where((tx) {
return tx.date.isAfter(
DateTime.now().subtract(
Duration(days: 7),
),
);
}).toList();
}
void _addNewTransaction(
String txTitle, double txAmount, DateTime chosenDate) {
final newTx = Transaction(
title: txTitle,
amount: txAmount,
date: chosenDate,
id: DateTime.now().toString(),
);
setState(() {
_userTransactions.add(newTx);
});
}
void _startAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(_addNewTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
void _deleteTransaction(String id) {
setState(() {
_userTransactions.removeWhere((tx) => tx.id == id);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Personal Expenses',
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
],
),
body: SingleChildScrollView(
child: Column(
// mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Chart(_recentTransactions),
TransactionList(_userTransactions, _deleteTransaction),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
);
}
}
#new_transaction.dart file
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:flutter/src/widgets/framework.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
#override
_NewTransactionState createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
late DateTime _selectedDate;
void initState() {
_selectedDate:
DateTime.now();
super.initState();
}
void _submitData() {
if (_amountController.text.isEmpty) {
return;
}
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
if (enteredTitle.isEmpty || enteredAmount <= 0 || _selectedDate == null) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
_selectedDate,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
print('...');
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
// onChanged: (val) => amountInput = val,
),
Container(
height: 70,
child: Row(
children: <Widget>[
Expanded(
child: Text(
_selectedDate == null
? 'No Date Chosen!'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}',
),
),
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text(
'Choose Date',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
onPressed: _presentDatePicker,
),
],
),
),
RaisedButton(
child: Text('Add Transaction'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button?.color,
onPressed: _submitData,
),
],
),
),
);
}
#override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
.add(DiagnosticsProperty<DateTime>('_selectedDate', _selectedDate));
}
}
#transaction_list.dart file
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/tranasction.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
TransactionList(
this.transactions, void Function(String id) deleteTransaction);
#override
Widget build(BuildContext context) {
return Container(
height: 300,
child: transactions.isEmpty
? Column(
children: <Widget>[
Text(
'No transactions added yet!',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(
height: 20,
),
Container(
height: 200,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
)),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(
vertical: 8,
horizontal: 5,
),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(6),
child: FittedBox(
child: Text('\$${transactions[index].amount}'),
),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.titleMedium,
),
subtitle: Text(
DateFormat.yMMMd().format(transactions[index].date),
),
),
);
},
itemCount: transactions.length,
),
);
}
}
#chart.dart file
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/tranasction.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
TransactionList(
this.transactions, void Function(String id) deleteTransaction);
#override
Widget build(BuildContext context) {
return Container(
height: 300,
child: transactions.isEmpty
? Column(
children: <Widget>[
Text(
'No transactions added yet!',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(
height: 20,
),
Container(
height: 200,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
)),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(
vertical: 8,
horizontal: 5,
),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(6),
child: FittedBox(
child: Text('\$${transactions[index].amount}'),
),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.titleMedium,
),
subtitle: Text(
DateFormat.yMMMd().format(transactions[index].date),
),
),
);
},
itemCount: transactions.length,
),
);
}
}
#chartbar.dart file
import 'package:flutter/material.dart';
class ChartBar extends StatelessWidget {
final String label;
final double spendingAmount;
final double spendingPctOfTotal;
ChartBar(this.label, this.spendingAmount, this.spendingPctOfTotal);
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
height: 20,
child: FittedBox(
child: Text('\$${spendingAmount.toStringAsFixed(0)}'),
),
),
SizedBox(
height: 4,
),
Container(
height: 60,
width: 10,
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 1.0),
color: Color.fromRGBO(220, 220, 220, 1),
borderRadius: BorderRadius.circular(10),
),
),
FractionallySizedBox(
heightFactor: spendingPctOfTotal,
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10),
),
),
),
],
),
),
SizedBox(
height: 4,
),
Text(label),
],
);
}
}
#transaction.dart file
**i am using the latest version of flutter
and using android studio as emulator,
and using vs code as code editor my code has no errors,
but i keep getting this error after many attempts
i tested using real android device too but nothing changed error message:'package:flutter/src/widgets/framework.dart':failed
assertion:line4864 pos 12:'child==_child':is not true.
see also https://flutter.dev/docs/testing/errors **

_CastError (Null check operator used on a null value) when using get.dart method

import 'package:calendar_app/consts/routes.dart';
import 'package:calendar_app/controller/task_controller.dart';
import 'package:calendar_app/models/task.dart';
import 'package:calendar_app/services/notification_service.dart';
import 'package:calendar_app/widgets/button.dart';
import 'package:calendar_app/widgets/task_tile.dart';
import 'package:date_picker_timeline/date_picker_timeline.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:intl/intl.dart';
import 'dart:developer' as devtools show log;
import 'package:get/get.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
DateTime _selectDate = DateTime.now();
final _taskController = Get.put(TaskController());
var notif;
#override
void initState() {
super.initState();
notif = Notif();
notif.initializeNotification();
notif.requestIOSPermissions();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 202, 202, 202),
body: Column(
children: [
Container(
margin: const EdgeInsets.fromLTRB(20, 50, 20, 0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
// Date
DateFormat.yMMMMd().format(DateTime.now()),
style: const TextStyle(
fontSize: 20,
),
),
const SizedBox(
height: 10,
),
const Text(
// Today
'Today',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
],
),
MyButton(
// Add Task
label: '+ Add Task',
onPressed: () async {
await Navigator.of(context).pushNamed(
addTaskRoute,
// (route) => false,
);
},
),
],
),
const SizedBox(
height: 20,
),
DatePicker(
// Calendar
DateTime.now(),
height: 100,
width: 80,
initialSelectedDate: DateTime.now(),
selectionColor: const Color.fromARGB(255, 12, 103, 179),
selectedTextColor: Colors.white,
dateTextStyle: const TextStyle(
fontSize: 35,
color: Colors.grey,
),
dayTextStyle: const TextStyle(
fontSize: 15,
color: Colors.grey,
),
monthTextStyle: const TextStyle(
fontSize: 15,
color: Colors.grey,
),
onDateChange: (date) {},
),
const SizedBox(
height: 20,
),
],
),
),
_showTasks(),
],
),
);
}
_showTasks() {
return Expanded(
child: Obx(
() {
return ListView.builder(
itemCount: _taskController.taskList.length,
itemBuilder: (_, index) {
devtools.log(_taskController.taskList.length.toString());
return AnimationConfiguration.staggeredList(
position: index,
child: SlideAnimation(
child: FadeInAnimation(
child: Row(
children: [
GestureDetector(
onTap: () {
devtools.log('tapped');
_showBottomSheet(
context,
_taskController.taskList[index],
);
},
child: TaskTile(
_taskController.taskList[index],
),
)
],
),
),
),
);
},
);
},
),
);
}
_showBottomSheet(BuildContext context, Task task) {
Get.bottomSheet(
Container(
padding: const EdgeInsets.only(top: 3),
height: task.isCompleted == 1
? MediaQuery.of(context).size.height * 0.25
: MediaQuery.of(context).size.height * 0.35,
color: Colors.white,
),
);
}
_bottomSheetButton({
required String label,
required Function()? onTap,
required Color color,
bool isClose = false,
required BuildContext context,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4),
height: 55,
width: MediaQuery.of(context).size.width * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: isClose == true ? Colors.red : color,
),
borderRadius: BorderRadius.circular(20),
color: isClose == true ? Colors.red : color,
),
),
);
}
}
When I'm clicking on container it throwing an exception saying:
_CastError (Null check operator used on a null value)
I didn't use any null operators in here
Is this a problem with Get.bottomsheet method or what?<br?
Exception showing _showBottomSheet has something wrong I mean null operator or whatever
Can you please help me go through this?
in your method _showBottomSheet, Task is required variable.
_taskController.taskList[index] -> this is probably null, you should debug this.
In your method, you can set Task as optional, like this: Task? task, and call your method like this:
_showBottomSheet(
context,
_taskController.taskList?[index],
);
and then:
_showBottomSheet(BuildContext context, Task? task) {
Get.bottomSheet(
Container(
padding: const EdgeInsets.only(top: 3),
height: task?.isCompleted == 1
? MediaQuery.of(context).size.height * 0.25
: MediaQuery.of(context).size.height * 0.35,
color: Colors.white,
),
);
}