RangeError (index): Invalid Value: Only valid value is 0: 1 error in MaterialApp - flutter

i'm pretty new to programming and currently facing an issue where one of my screens wont display. The screen is sort of like a shopping cart screen where it displays the items the user has chosen. I'm very lost because for some reason flutter tells me the error is located in MaterialApp in main.
Here is my main.dart
import 'package:eat_easy_project/assistantMethod/shopping_List_Counter.dart';
import 'package:eat_easy_project/global/global.dart';
import 'package:eat_easy_project/splashScreen/splash_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:provider/provider.dart';
Future<void> main() async
{
WidgetsFlutterBinding.ensureInitialized();
sharedPreferences = await SharedPreferences.getInstance();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (c)=> ShoppingListCounter()),
],
child: MaterialApp(
title: 'EatEasy Project',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MySplashScreen(),
),
);
}
}
and below is the cart screen where it the other code where it shoul've displayed
import 'package:eat_easy_project/models/ingredients.dart';
import 'package:flutter/material.dart';
class ShoppingListDesign extends StatefulWidget
{
final Ingredients? model;
BuildContext? context;
final List <int>? separateIngredientQuantitiesList;
ShoppingListDesign({
this.model,
this.context,
this.separateIngredientQuantitiesList,
});
#override
State<ShoppingListDesign> createState() => _ShoppingListDesignState();
}
class _ShoppingListDesignState extends State<ShoppingListDesign> {
#override
Widget build(BuildContext context) {
return InkWell(
splashColor: Colors.cyan,
child: Padding(
padding: const EdgeInsets.all(6.0),
child: Container(
height: 165,
width: MediaQuery.of(context).size.width,
child: Row(
children: [
Image.network(widget.model!.ingredientAvatarUrl!, width: 140, height: 120,),
const SizedBox(width: 6,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.model!.ingredientName!,
style: const TextStyle(
color: Colors.black,
fontSize: 16,
fontFamily: "Kiwi",
),
),
const SizedBox(
height: 1.0,
),
Row(
children: [
const Text(
"x ",
style: TextStyle(
color: Colors.black,
fontSize: 25,
fontFamily: "Acme",
),
),
Text(
widget.separateIngredientQuantitiesList.toString(),
style: const TextStyle(
color: Colors.black,
fontSize: 25,
fontFamily: "Acme",
),
),
],
),
Row(
children: [
const Text(
"Price: ",
style: TextStyle(
fontSize: 15,
color: Colors.grey,
),
),
const Text(
"RM ",
style: TextStyle(
fontSize: 15,
color: Colors.grey,
),
),
Text(
widget.model!.ingredientPrice.toString(),
style: const TextStyle(
fontSize: 15,
color: Colors.grey,
),
),
],
)
],
),
],
),
),
),
);
}
}
I'm following a guide from udemy to help me code and for some reason even though I copied the exact same code with minor adjustments, I still got this error. My database json is located in firebase.
Error in detail:
enter image description here
Error for assitantMethod led me to var quanNumber = int.parse(listIngredientCharacters1.toString());
separateIngredientUIDs()
{
List<String> separateIngredientUIDsList=[], defaultIngredientList=
[];
int i=0;
defaultIngredientList =
sharedPreferences!.getStringList("userShoppingList")!;
for(i; i<defaultIngredientList.length; i++)
{
String ingredient = defaultIngredientList[i].toString();
var pos = ingredient.lastIndexOf(":");
String getIngredientID = (pos != -1) ? ingredient.substring(0, pos)
: ingredient;
print("\nThis is ingredientID now = " + getIngredientID);
separateIngredientUIDsList.add(getIngredientID);
}
print("\nThis is Ingredients List now = " );
print(separateIngredientUIDsList);
return separateIngredientUIDsList;
}
addIngredientToCart(String? ingredientUID, BuildContext context, int
ingredientCounter)
{
List<String>? tempList =
sharedPreferences!.getStringList("userShoppingList");
tempList!.add(ingredientUID! + ":$ingredientCounter");
FirebaseFirestore.instance.collection("user")
.doc(firebaseAuth.currentUser!.uid).update({
"userShoppingList": tempList,
}).then((value)
{
Fluttertoast.showToast(msg: "Ingredient Added Successfully.");
sharedPreferences!.setStringList("userShoppingList", tempList);
//update badge
Provider.of<ShoppingListCounter>(context, listen:
false).displayShoppingListIngredientNumber();
});
}
separateIngredientQuantities()
{
List<int> separateIngredientQuantityList=[];
List<String> defaultIngredientList=[];
int i=0;
defaultIngredientList =
sharedPreferences!.getStringList("userShoppingList")!;
for(i; i<defaultIngredientList.length; i++)
{
String ingredient = defaultIngredientList[i].toString();
List<String> listIngredientCharacters =
ingredient.split(":").toList();
var quanNumber = int.parse(listIngredientCharacters[0].toString());
print("\nThis is Quantity Number = " + quanNumber.toString());
separateIngredientQuantityList.add(quanNumber);
}
print("\nThis is Quantity List now = " );
print(separateIngredientQuantityList);
return separateIngredientQuantityList;
}
Error for shoppinglistscreen led me to separateIngredientQuantities();
class ShoppingListScreen extends StatefulWidget {
Ingredients? model;
ShoppingListScreen({this.model});
#override
State<ShoppingListScreen> createState() => _ShoppingListScreenState();
}
class _ShoppingListScreenState extends State<ShoppingListScreen>
{
#override
void initState() {
super.initState();
separateIngredientQuantities();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar
(
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(255, 192, 234, 240),
Color.fromARGB(255, 108, 173, 70),
],
begin: FractionalOffset(0.0, 0.0),
end: FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp,
)
),
),
title: const Text(
"EatEasy",
style: TextStyle(color: Colors.white, fontWeight:
FontWeight.bold,)
),
centerTitle: true,
automaticallyImplyLeading: true,
actions: [
Stack(
children: [
IconButton(
icon: const Icon(Icons.shopping_cart, color: Colors.cyan,),
onPressed: ()
{
Navigator.push(context, MaterialPageRoute(builder: (c)=>
ShoppingListScreen(model: widget.model,)));
},
),
Positioned(
child: Stack(
children: [
const Icon(
Icons.brightness_1,
size: 20.0,
color: Color.fromARGB(255, 29, 88, 31),
),
Positioned(
top: 3,
right: 4,
child: Center(
child: Consumer<ShoppingListCounter>(
builder: (context, counter, c)
{
return Text(
counter.count.toString(),
style: const TextStyle(color: Color.fromARGB(255, 209, 218, 226)),
);
}
),
),
),
],
),
),
],
),
],
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(width: 10,),
Align(
alignment: Alignment.bottomLeft,
child: FloatingActionButton.extended(
label: const Text("Clear List", style: TextStyle(fontSize: 16),),
backgroundColor: Colors.cyan,
icon: const Icon(Icons.clear_all),
onPressed: ()
{
},
),
),
Align(
alignment: Alignment.bottomLeft,
child: FloatingActionButton.extended(
label: const Text("Calculate Total", style: TextStyle(fontSize: 16),),
backgroundColor: Colors.cyan,
icon: const Icon(Icons.calculate),
onPressed: ()
{
},
),
)
],
),
body: CustomScrollView(
slivers: [
//overall total amount
SliverPersistentHeader(
pinned: true,
delegate: TextWidgetHeader(title: "Total Amount = 120"),
),
//display cart ingredients with quantity
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("ingredients")
.where("ingredientUID", whereIn: separateIngredientUIDs())
.orderBy("ingredientPrice", descending: true)
.snapshots(),
builder: (context, snapshot)
{
return !snapshot.hasData
? SliverToBoxAdapter(child: Center(child:
circularProgress()),)
: snapshot.data!.docs.length == 0
? //startBuildingList
Container()
: SliverList(
delegate: SliverChildBuilderDelegate((context, index)
{
Ingredients model = Ingredients.fromJson(
snapshot.data!.docs[index].data()! as Map<String,
dynamic>,
);
return ShoppingListDesign(
model: model,
context: context,
separateIngredientQuantitiesList: [index] ,
);
},
//childCount: snapshot.hasData ?
snapshot.data!.docs.length : 0,
),
);
},
),
],
),
);
}
}

Related

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

stack overflow error:The following StackOverflowError was thrown building OnboardingView(dirty): Stack Overflow

there is also a terminal output....
I have this problem after copying and pasting a code from out side the project .
I think it had to do with routes or the GetX packege because I dont know how to use correctly so it may be the problem. and there is also the routes code i have included it here and I think it may be something there and not forgetting the cntrollers code ..I have also included it here
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import '../controllers/onboarding_controller.dart';
class OnboardingView extends GetView<OnboardingController> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
PageView.builder(
controller: controller.onboardingController.pageController,
onPageChanged: controller.onboardingController.selectedPageIndex,
itemCount: controller.onboardingController.onboardingPages.length,
itemBuilder: (context, index) {
return Stack(
children: [
Image.asset(
controller.onboardingController.onboardingPages[index]
.imageAsset,
fit: BoxFit.cover,
),
Align(
alignment: const AlignmentDirectional(0, 0.1),
child: Text(
controller.onboardingController.onboardingPages[index]
.title,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 57,
),
)),
Align(
alignment: const AlignmentDirectional(0, 0.40),
child: Text(
controller.onboardingController.onboardingPages[index]
.description,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w400,
fontFamily: 'Inter',
fontSize: 18,
),
),
),
],
);
}),
Align(
alignment: const AlignmentDirectional(0, 0.55),
child: SmoothPageIndicator(
effect: ExpandingDotsEffect(),
controller: controller.onboardingController.pageController,
count: 3)),
// Align(
// alignment: const AlignmentDirectional(0, 0.55),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: List.generate(
// _controller.onboardingPages.length,
// (index) => Obx(() {
// return Container(
// margin: const EdgeInsets.all(4),
// width: 12,
// height: 12,
// decoration: BoxDecoration(
// color: _controller.selectedPageIndex.value == index
// ? Colors.white
// : Colors.grey,
// shape: BoxShape.circle,
// ),
// );
// })),
// ),
// ),
Align(
//
alignment: const AlignmentDirectional(0, 0.75),
child: Obx(() {
return controller.onboardingController.isLastPage
? ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purple,
fixedSize: const Size(350, 45)),
onPressed: () {},
// onPressed: () => Get.to(LogInPage()),
child: const Text(
"LogIn",
style: TextStyle(fontSize: 20, letterSpacing: 2),
))
: ElevatedButton(
onPressed: controller.onboardingController.forwardAction,
style: ElevatedButton.styleFrom(
side: const BorderSide(color: Colors.white),
backgroundColor: Colors.transparent,
fixedSize: const Size(350, 45)),
child: const Text(
'Next',
style: TextStyle(fontSize: 20, letterSpacing: 2),
),
);
}),
),
Align(
//
alignment: const AlignmentDirectional(0, 0.90),
child: Obx(() {
return controller.onboardingController.isLastPage
? ElevatedButton(
style: ElevatedButton.styleFrom(
side: const BorderSide(color: Colors.white),
backgroundColor: Colors.transparent,
fixedSize: const Size(350, 45)),
onPressed: () {
// Get.to(SignUpPage());
},
child: Text("create an account"))
: ElevatedButton(
style: ElevatedButton.styleFrom(
side: const BorderSide(color: Colors.white),
backgroundColor: Colors.transparent,
fixedSize: const Size(350, 45)),
onPressed: () => controller
.onboardingController.pageController
.jumpToPage(2),
child: Text(
'Skip',
style: const TextStyle(fontSize: 20, letterSpacing: 1),
),
);
}),
),
Align(
alignment: const AlignmentDirectional(0, 0.30),
child: Obx(() {
return Text(
controller.onboardingController.isLastPage
? 'The only shopping \nApp you need '
: '',
style: const TextStyle(
color: Colors.white,
fontSize: 34,
fontWeight: FontWeight.w600),
);
}),
),
],
),
);
}
}
import 'package:azyaa/app/data/onboarding_data.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class OnboardingController extends GetxController {
final onboardingController = OnboardingController();
var selectedPageIndex = 0.obs;
bool get isLastPage => selectedPageIndex.value == onboardingPages.length - 1;
var pageController = PageController();
forwardAction() {
if (isLastPage) {
//do this
} else
pageController.nextPage(duration: 300.milliseconds, curve: Curves.ease);
}
List<OnboardingInfo> onboardingPages = [
OnboardingInfo("assets/1.png", "Shop better,\nlook good.\n",
"Buy pre-loved Gucci, Louis Vuitton,\nOff-White... 12,000 brands up to 70%\noff retail price, all great for the planet."),
OnboardingInfo("assets/2.png", "Delivered\nto your spot",
"Buy pre-loved Gucci, Louis Vuitton,\nOff-White... 12,000 brands up to 70%\noff retail price, all great for the planet."),
OnboardingInfo("assets/3.png", "", ""),
];
#override
void onInit() {
super.onInit();
}
#override
void onReady() {
super.onReady();
}
#override
void onClose() {}
}
part of 'app_pages.dart';
// DO NOT EDIT. This is code generated via package:get_cli/get_cli.dart
abstract class Routes {
Routes._();
static const HOME = _Paths.HOME;
static const ONBOARDING = _Paths.ONBOARDING;
}
abstract class _Paths {
_Paths._();
static const HOME = '/home';
static const ONBOARDING = '/onboarding';
}
import 'package:get/get.dart';
import '../modules/home/bindings/home_binding.dart';
import '../modules/home/bindings/home_binding.dart';
import '../modules/home/views/home_view.dart';
import '../modules/home/views/home_view.dart';
import '../modules/onboarding/bindings/onboarding_binding.dart';
import '../modules/onboarding/views/onboarding_view.dart';
part 'app_routes.dart';
class AppPages {
AppPages._();
static const INITIAL = Routes.ONBOARDING;
static final routes = [
GetPage(
name: _Paths.HOME,
page: () => HomeView(),
binding: HomeBinding(),
children: [
GetPage(
name: _Paths.HOME,
page: () => HomeView(),
binding: HomeBinding(),
),
],
),
GetPage(
name: _Paths.ONBOARDING,
page: () => OnboardingView(),
binding: OnboardingBinding(),
),
];
}
``
I am not sure but think the error has to do with routes ....I dont actually know

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.

Could not find the correct Provider<CartItemCounter> above this HomeScreen Widget

I keep on getting this problem:
Unhandled Exception: Error: Could not find the correct Provider above this HomeScreen Widget
Since I am trying to implement Cart Item Counter, there is this bug.
Here is my code:
Main.dart
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
sharedPreferences = await SharedPreferences.getInstance();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (c) => CartItemCounter()),
ChangeNotifierProvider(create: (c) => TotalAmount()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Users App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MySplashScreen(),
),
);
}
}
Below is my App Bar, This is where i send users to Cart:
class MyAppBar extends StatefulWidget with PreferredSizeWidget {
final PreferredSizeWidget? bottom;
final String? sellerUID;
MyAppBar({this.bottom, this.sellerUID});
#override
_MyAppBarState createState() => _MyAppBarState();
#override
Size get preferredSize => bottom == null
? Size(56, AppBar().preferredSize.height)
: Size(56, 80 + AppBar().preferredSize.height);
}
class _MyAppBarState extends State<MyAppBar> {
#override
Widget build(BuildContext context) {
return AppBar(
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.cyan,
Colors.amber,
],
begin: FractionalOffset(0.0, 0.0),
end: FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp,
)),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
),
title: const Text(
"iFood",
style: TextStyle(fontSize: 45, fontFamily: "Signatra"),
),
centerTitle: true,
automaticallyImplyLeading: true,
actions: [
Stack(
children: [
IconButton(
icon: const Icon(
Icons.shopping_cart,
color: Colors.cyan,
),
onPressed: () {
//send user to cart screen
Navigator.push(
context,
MaterialPageRoute(
builder: (c) =>
CartScreen(sellerUID: widget.sellerUID)));
},
),
Positioned(
child: Stack(
children: [
const Icon(
Icons.brightness_1,
size: 20.0,
color: Colors.green,
),
Positioned(
top: 3,
right: 4,
child: Center(
child: Consumer<CartItemCounter>(
builder: (context, counter, c) {
return Text(
counter.count.toString(),
style: const TextStyle(
color: Colors.white, fontSize: 12),
);
},
),
),
),
],
),
),
],
),
],
);
}
}
Following is My Cart Screen:
I want to display cart items with quantity number
class CartScreen extends StatefulWidget {
final String? sellerUID;
CartScreen({this.sellerUID});
#override
_CartScreenState createState() => _CartScreenState();
}
class _CartScreenState extends State<CartScreen> {
List<int>? separateItemQuantityList;
num totalAmount = 0;
#override
void initState() {
super.initState();
totalAmount = 0;
Provider.of<TotalAmount>(context, listen: false).displayTotalAmount(0);
separateItemQuantityList = separateItemQuantities();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.cyan,
Colors.amber,
],
begin: FractionalOffset(0.0, 0.0),
end: FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp,
)),
),
leading: IconButton(
icon: const Icon(Icons.clear_all),
onPressed: () {
clearCartNow(context);
},
),
title: const Text(
"iFood",
style: TextStyle(fontSize: 45, fontFamily: "Signatra"),
),
centerTitle: true,
automaticallyImplyLeading: true,
actions: [
Stack(
children: [
IconButton(
icon: const Icon(
Icons.shopping_cart,
color: Colors.cyan,
),
onPressed: () {
print("clicked");
},
),
Positioned(
child: Stack(
children: [
const Icon(
Icons.brightness_1,
size: 20.0,
color: Colors.green,
),
Positioned(
top: 3,
right: 4,
child: Center(
child: Consumer<CartItemCounter>(
builder: (context, counter, c) {
return Text(
counter.count.toString(),
style: const TextStyle(
color: Colors.white, fontSize: 12),
);
},
),
),
),
],
),
),
],
),
],
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const SizedBox(
width: 10,
),
Align(
alignment: Alignment.bottomLeft,
child: FloatingActionButton.extended(
label: const Text(
"Clear Cart",
style: TextStyle(fontSize: 16),
),
backgroundColor: Colors.cyan,
icon: const Icon(Icons.clear_all),
onPressed: () {
clearCartNow(context);
Navigator.push(context,
MaterialPageRoute(builder: (c) => const MySplashScreen()));
Fluttertoast.showToast(msg: "Cart has been cleared.");
},
),
),
Align(
alignment: Alignment.bottomLeft,
child: FloatingActionButton.extended(
label: const Text(
"Check Out",
style: TextStyle(fontSize: 16),
),
backgroundColor: Colors.cyan,
icon: const Icon(Icons.navigate_next),
onPressed: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (c) => AddressScreen(
// totalAmount: totalAmount.toDouble(),
// sellerUID: widget.sellerUID,
// ),
// ),
// );
},
),
),
],
),
body: CustomScrollView(
slivers: [
//overall total amount
SliverPersistentHeader(
pinned: true, delegate: TextWidgetHeader(title: "My Cart List")),
SliverToBoxAdapter(
child: Consumer2<TotalAmount, CartItemCounter>(
builder: (context, amountProvider, cartProvider, c) {
return Padding(
padding: const EdgeInsets.all(8),
child: Center(
child: cartProvider.count == 0
? Container()
: Text(
"Total Price: " + amountProvider.tAmount.toString(),
style: const TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
);
}),
),
//display cart items with quantity number
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("items")
.where("itemID", whereIn: separateItemIDs())
.orderBy("publishedDate", descending: true)
.snapshots(),
builder: (context, snapshot) {
return !snapshot.hasData
? SliverToBoxAdapter(
child: Center(
child: circularProgress(),
),
)
: snapshot.data!.docs.length == 0
? //startBuildingCart()
Container()
: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
Items model = Items.fromJson(
snapshot.data!.docs[index].data()!
as Map<String, dynamic>,
);
if (index == 0) {
totalAmount = 0;
totalAmount = totalAmount +
(model.price! *
separateItemQuantityList![index]);
} else {
totalAmount = totalAmount +
(model.price! *
separateItemQuantityList![index]);
}
if (snapshot.data!.docs.length - 1 == index) {
WidgetsBinding.instance
.addPostFrameCallback((timeStamp) {
Provider.of<TotalAmount>(context,
listen: false)
.displayTotalAmount(
totalAmount.toDouble());
});
}
return CartItemDesign(
model: model,
context: context,
quanNumber: separateItemQuantityList![index],
);
},
childCount: snapshot.hasData
? snapshot.data!.docs.length
: 0,
),
);
},
),
],
),
);
}
}
It's hard to tell what is the problem without looking at the whole source code.
My guess is that you need to pass the ChangeNotifierProvider instance across routes (basically whenever you do Navigator.push()).
Check out this answer.
When passing ChangeNotifierProvider in main
Pass it like this
ChangeNotifierProvider(
create : (context) => CartItemCounter(),
child : CartScreen (), // screen where you want to access the Provider
),

flutter: Edit a ListView Item

i want to edit a listview item when i click on it. I managed (with inkwell) that when I click on a listview item, the bottomsheet opens again where I also create new listview items, but I just can't edit it. I've tried everything I know (I don't know much I'm a beginner). here my codes.
--main.dart--
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import '/model/transaction.dart';
import '/widget/chart.dart';
import '/widget/new_transaction.dart';
import '/widget/transactoin_list.dart';
void main() {
// WidgetsFlutterBinding.ensureInitialized();
// SystemChrome.setPreferredOrientations(
// [
// DeviceOrientation.portraitUp,
// DeviceOrientation.portraitDown,
// ],
// );
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale("de"),
Locale("en"),
],
debugShowCheckedModeBanner: false,
title: "URLI",
theme: ThemeData(
primarySwatch: Colors.lightGreen,
fontFamily: "JosefinSans",
textTheme: ThemeData()
.textTheme
.copyWith(
headline4: const TextStyle(
fontFamily: "Tochter",
fontSize: 21,
),
headline5: const TextStyle(
fontFamily: "Bombing",
fontSize: 27,
letterSpacing: 3,
),
headline6: const TextStyle(
fontSize: 21,
fontWeight: FontWeight.w900,
),
)
.apply(
bodyColor: Colors.orangeAccent,
displayColor: Colors.orangeAccent.withOpacity(0.5),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
onPrimary: Colors.white,
primary: Theme.of(context).appBarTheme.backgroundColor,
textStyle: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
appBarTheme: const AppBarTheme(
titleTextStyle: TextStyle(
fontSize: 60,
fontFamily: "Tochter",
),
),
),
home: const AusgabenRechner(),
);
}
}
class AusgabenRechner extends StatefulWidget {
const AusgabenRechner({Key? key}) : super(key: key);
#override
State<AusgabenRechner> createState() => _AusgabenRechnerState();
}
class _AusgabenRechnerState extends State<AusgabenRechner> {
void _submitAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(addNewTx: _addNewTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
bool _showChart = false;
final List<Transaction> _userTransactions = [
// Transaction(
// id: "tx1",
// tittel: "Schuhe",
// preis: 99.99,
// datum: DateTime.now(),
// ),
// Transaction(
// id: "tx2",
// tittel: "Jacke",
// preis: 39.99,
// datum: DateTime.now(),
// ),
];
List<Transaction> get _recentTransactions {
return _userTransactions
.where(
(tx) => tx.datum.isAfter(
DateTime.now().subtract(
const Duration(days: 7),
),
),
)
.toList();
}
void _addNewTransaction(
String txTittel,
double txPreis,
DateTime choosenDate,
) {
final newTx = Transaction(
id: DateTime.now().toString(),
tittel: txTittel,
preis: txPreis,
datum: choosenDate,
);
setState(() {
_userTransactions.add(newTx);
});
}
void _deletedTransaction(String id) {
setState(() {
_userTransactions.removeWhere((tdddx) => tdddx.id == id);
});
}
#override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
final isInLandscape = mediaQuery.orientation == Orientation.landscape;
final appBar = AppBar(
centerTitle: true,
toolbarHeight: 99,
actions: [
IconButton(
onPressed: () => _submitAddNewTransaction(context),
icon: const Icon(
Icons.add,
color: Colors.white,
),
),
],
title: const Text(
"Ausgaben",
),
);
final txListWidget = SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.45,
child: TransactionList(
transaction: _userTransactions,
delettx: _deletedTransaction,
showNewTransaction: _submitAddNewTransaction,
),
);
return Scaffold(
appBar: appBar,
body: SingleChildScrollView(
child: Column(
children: [
if (isInLandscape)
SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.2,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Chart anzeigen",
style: Theme.of(context).textTheme.headline5,
),
const SizedBox(width: 9),
Switch.adaptive(
inactiveTrackColor:
Theme.of(context).primaryColor.withOpacity(0.3),
activeColor: Theme.of(context).primaryColor,
value: _showChart,
onChanged: (val) {
setState(() {
_showChart = val;
});
},
),
],
),
),
if (!isInLandscape)
SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.24,
child: Chart(
recentTransactions: _recentTransactions,
),
),
if (!isInLandscape)
SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.65,
child: txListWidget),
if (isInLandscape)
_showChart
? SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.51,
child: Chart(
recentTransactions: _recentTransactions,
),
)
: SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.81,
child: txListWidget)
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: const Icon(
Icons.add,
color: Colors.white,
),
onPressed: () => _submitAddNewTransaction(context),
),
);
}
}
--transaction_list.dart--
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '/model/transaction.dart';
class TransactionList extends StatefulWidget {
const TransactionList({
Key? key,
required this.transaction,
required this.delettx,
required this.showNewTransaction,
}) : super(key: key);
final List<Transaction> transaction;
final Function delettx;
final Function showNewTransaction;
#override
State<TransactionList> createState() => _TransactionListState();
}
class _TransactionListState extends State<TransactionList> {
#override
Widget build(BuildContext context) {
return widget.transaction.isEmpty
? LayoutBuilder(
builder: (ctx, contrains) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Keine Daten vorhanden!",
style: Theme.of(context).textTheme.headline6,
),
const SizedBox(
height: 30,
),
SizedBox(
height: contrains.maxHeight * 0.45,
child: Image.asset(
"assets/images/schlafen.png",
fit: BoxFit.cover,
),
)
],
);
},
)
: Align(
alignment: Alignment.topCenter,
child: ListView.builder(
shrinkWrap: true,
reverse: true,
itemCount: widget.transaction.length,
itemBuilder: (ctx, index) {
return InkWell(
onLongPress: () => widget.showNewTransaction(ctx),
child: Card(
elevation: 5,
child: ListTile(
leading: CircleAvatar(
radius: 33,
child: Padding(
padding: const EdgeInsets.all(9.0),
child: FittedBox(
child: Row(
children: [
Text(
widget.transaction[index].preis
.toStringAsFixed(2),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 24,
),
),
const Text(
"€",
style: TextStyle(
fontSize: 21,
),
)
],
),
),
),
),
title: Text(
widget.transaction[index].tittel,
style: Theme.of(context).textTheme.headline6,
),
subtitle: Text(
DateFormat.yMMMMd("de")
.format(widget.transaction[index].datum),
style: Theme.of(context).textTheme.headline4,
),
trailing: MediaQuery.of(context).size.width > 460
? TextButton.icon(
onPressed: () =>
widget.delettx(widget.transaction[index].id),
icon: const Icon(
Icons.delete_outline,
),
label: const Text("Löschen"),
style: TextButton.styleFrom(
primary: Colors.red,
),
)
: IconButton(
onPressed: () =>
widget.delettx(widget.transaction[index].id),
icon: const Icon(
Icons.delete_outline,
color: Colors.red,
),
),
),
),
);
},
),
);
}
}
--new_transaction.dart--
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
const NewTransaction({Key? key, required this.addNewTx}) : super(key: key);
final Function addNewTx;
#override
State<NewTransaction> createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _tittelcontroller = TextEditingController();
final _preiscontroller = TextEditingController();
DateTime? _selectedDate;
void _submitData() {
final enteredTittel = _tittelcontroller.text;
final enteredPreis = double.parse(_preiscontroller.text);
if (_preiscontroller.text.isEmpty) {
return;
}
if (enteredTittel.isEmpty || enteredPreis <= 0 || _selectedDate == null) {
return;
}
widget.addNewTx(
_tittelcontroller.text,
double.parse(_preiscontroller.text),
_selectedDate,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2022),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
bottom: false,
child: SingleChildScrollView(
child: Container(
//height: MediaQuery.of(context).size.height * 0.5,
padding: EdgeInsets.only(
top: 10,
left: 18,
right: 18,
bottom: MediaQuery.of(context).viewInsets.bottom + 10,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
TextButton(
onPressed: _submitData,
child: Text(
"hinzufügen",
style: Theme.of(context).textTheme.headlineSmall,
),
),
TextField(
controller: _tittelcontroller,
onSubmitted: (_) => _submitData(),
decoration: const InputDecoration(
label: Text("Tittel"),
),
),
TextField(
controller: _preiscontroller,
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
onSubmitted: (_) => _submitData(),
decoration: const InputDecoration(
label: Text("Preis"),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 66),
child: Center(
child: Column(
children: [
Text(
_selectedDate == null
? "Kein Datum ausgewählt"
: DateFormat.yMMMMEEEEd("de")
.format(_selectedDate!),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
const SizedBox(
height: 21,
),
ElevatedButton(
style: Theme.of(context).elevatedButtonTheme.style,
onPressed: _presentDatePicker,
child: const Text("Datum wählen"),
),
],
),
),
)
],
),
),
),
);
}
}
EN: Here is an excample code, how i would solve this, when i understood the problem. The passing of the variables to the new Class is a bit differnent then in your Code but it works the same.
DE: So hier ist jetzt ein Beispielcode, wie ich es lösen würde, wenn ich das Problem richtig verstanden habe, dabei werden die Variabeln etwas anders als bei dir in die neue Klasse übergeben, funktioniert aber gleich
class testListview extends StatefulWidget {
var transaction;
var delettx;
var showNewTransaction;
//Passing the data to new Class
testListview(this.transaction, this.delettx,
this.showNewTransaction);
#override
State<testListview> createState() => _testListviewState();
}
class _testListviewState extends State<testListview> {
var transaction;
var delettx;
var showNewTransaction;
//Pass the data into the State of the new Class
_testListviewState(this.transaction, this.delettx,
this.showNewTransaction);
var transaction_2;
//The init state will be called in the first initialization of
//the Class
#override
void initState() {
//Pass your transactions to a new variable
setState(() {
transaction_2 = transaction;
});
super.initState();
}
#override
Widget build(BuildContext context) {
return ListView.builder(itemBuilder: (BuildContext context,
index){
return TextButton(onPressed: (){
//Change the data with onPressed
setState(() {
transaction_2["preis"] = "500";
});
}, child: Text(transaction_2["preis"]));
});}}