Quantcast
Channel: Active questions tagged listview - Stack Overflow
Viewing all articles
Browse latest Browse all 611

Could not find the correct Provider above this HomeBody Widget | flutter

$
0
0

I have 2 function to build the tileWithCounter (listBuild,gridBuild) but only one of them works(gridBuild)

i copy the code in the first function to the second but that does not make it worksi know if i move the the provider to the main it will works but i dont need that i need to know what is the problem why this dont works

homeBody.dartimport 'dart:math';import 'package:achivement_box/db/sql.dart';import 'package:achivement_box/pages/homePage/Bodies/HomeBody/provider/levelProvider.dart';import 'package:flutter/material.dart';import 'package:provider/provider.dart';import '../../../../models/Coins.dart';import '../../../../models/PrimaryContainer.dart';import '../../../../models/habit.dart';import '../../../../models/levelBar.dart';import '../../../../rootProvider/habitProvider.dart';class HomeBody extends StatelessWidget {  const HomeBody({super.key});  final List<String> somethingChangedEveryTime = const ["Small daily habits lead to big achievements over time.","Every step you take brings you closer to your goal.","Consistency is the key to success; keep going!","Believe in yourself and all that you are capable of.","Celebrate every small victory; they add up to great success.","Focus on progress, not perfection.","Your only limit is your mind; think big!","Commit to your goals, and they will become your reality.","Stay motivated; your hard work will pay off.","Embrace challenges; they are opportunities to grow.","Stay disciplined, and success will follow.","Every habit you build strengthens your path to achievement.","Visualize your success and work towards it daily.","Remember, the journey is as important as the destination.","Push yourself; the results will be worth it.","Keep your goals in sight and your determination strong.","You have the power to create the life you want.","Stay positive; a positive mindset fuels progress.","Dedicate yourself to your goals, and they will be within reach.","Your achievements are the sum of your daily actions; make each day count.",  ];  Widget habitBuilder(context, habit) {    return Habit(      context: context,      categoryId: habit['Category'],      id: habit['Id'],      totalTimes: habit['count'] ?? 0,      hardness: habit['Hardness'],      iconId: habit['IconId'],      isBadHabit: habit['IsBad'] == 1 ? true : false,      name: habit['Name'],      price: habit['Price'],      priority: habit['Priority'],      timeInMinutes: habit['TimeInMinutes'],    );  }  @override  Widget build(BuildContext context) {    var habits = context.watch<HabitProvider>().Habits;    return ChangeNotifierProvider(      create: (context) => LevelProvider(),      child: Column(        children: [          const Padding(            padding: EdgeInsets.all(8.0),            child: Row(              mainAxisAlignment: MainAxisAlignment.spaceBetween,              children: [                LevelBar(                  canChange: true,                ),                CoinsBar(),              ],            ),          ),          Padding(            padding: const EdgeInsets.symmetric(horizontal: 8.0),            child: FittedBox(              child: Text(somethingChangedEveryTime[                  Random().nextInt(somethingChangedEveryTime.length - 1)]),            ),          ),          Expanded(            child: PrimaryContainer(              opacity: 0.1,              child: isListView()                  ? ListView.builder(                      itemBuilder: (child, index) =>                          habitBuilder(context, habits[index]),                      itemCount: habits.length,                      shrinkWrap: false,                    )                  : GridView.builder(                      itemBuilder: (context, index) =>                          habitBuilder(context, habits[index]),                      itemCount: habits.length,                      shrinkWrap: false,                      gridDelegate:                          const SliverGridDelegateWithMaxCrossAxisExtent(                        mainAxisSpacing: 5.0, // Vertical spacing between items                        crossAxisSpacing:                            5.0, // Horizontal spacing between items                        childAspectRatio: 110 / 165,                        maxCrossAxisExtent: 110, // Aspect ratio of the widgets                      )),            ),          ),        ],      ),    );  }}
tileWithCounter.dartimport 'package:achivement_box/db/sql.dart';import 'package:achivement_box/models/imageIcon.dart';import 'package:auto_size_text/auto_size_text.dart';import 'package:badges/badges.dart' as badges;import 'package:flutter/material.dart';import '../output/generated/icon_names.dart';import 'PrimaryContainer.dart';import 'my_toast.dart';abstract class TileWithCounter extends StatefulWidget {  TileWithCounter({    super.key,    required this.id,    required this.iconId,    required this.name,    required this.price,    required this.context,    required this.totalTimes,  });  void openEditPage();  void clicked();  late MyToast undoToast = MyToast(    title: Text(toastTitle),    button: TextButton(      onPressed: () {        undoToast.closeOverlay();        undo();      },      child: const Text("undo"),    ),  );  late String toastTitle;  void undo();  final int iconId;  final String name;  final int price;  final BuildContext context;  final int id;  static const double width = 100;  int totalTimes;  @override  State<TileWithCounter> createState() => _TileWithCounterVerticalState();}class _TileWithCounterVerticalState extends State<TileWithCounter> {  void used() {    widget.totalTimes++;    widget.clicked();    setState(() {});  }  Widget gridBuild() {    return badges.Badge(      position: badges.BadgePosition.topEnd(top: 2, end: 2),      badgeStyle: badges.BadgeStyle(        shape: badges.BadgeShape.circle,        badgeColor: Theme.of(context).primaryColor.withOpacity(0.6),        elevation: 0,      ),      badgeContent: SizedBox(        width: 20,        height: 20,        child: FittedBox(          child: Text("${widget.totalTimes}",            textAlign: TextAlign.center,          ),        ),      ),      child: GestureDetector(        onLongPress: widget.openEditPage,        onTap: used,        child: PrimaryContainer(          width: TileWithCounter.width,          height: 150, // Increase the height to provide more space          child: Column(            mainAxisSize: MainAxisSize.min,            mainAxisAlignment: MainAxisAlignment.spaceBetween,            children: [              const SizedBox(                height: 10,              ),              IconImage(                iconName: iconNames[widget.iconId],                size: 35,              ),              Padding(                padding:                    const EdgeInsets.symmetric(horizontal: 10, vertical: 2.5),                child: AutoSizeText(                  widget.name,                  maxLines: 2,                  textAlign: TextAlign.center,                  overflow: TextOverflow.ellipsis,                  minFontSize: 5,                  maxFontSize: 10,                ),              ),              Row(                mainAxisSize: MainAxisSize.max,                mainAxisAlignment: MainAxisAlignment.center,                children: [                  IconImage(                    iconName: "coin-front.png",                    size: 15,                  ),                  const SizedBox(                    width: 5,                  ),                  Text("${widget.price}",                    style: const TextStyle(fontSize: 12),                  ),                ],              ),              GestureDetector(                onTap: widget.openEditPage,                child: IconImage(iconName: "ellipsis-stroke.png", size: 15),              ),            ],          ),        ),      ),    );  }  Widget listBuild() {    /* return GestureDetector(      onLongPress: widget.openEditPage,      child: PrimaryContainer(          child: Padding(        padding: const EdgeInsets.symmetric(horizontal: 8.0),        child: Row(          children: [            IconImage(              iconName: iconNames[widget.iconId],              size: 35,            ),            Padding(              padding: const EdgeInsets.symmetric(horizontal: 10.0),              child: Column(                  crossAxisAlignment: CrossAxisAlignment.start,                  children: [                    Text(widget.name),                    Row(children: [                      IconImage(                        iconName: "coin-front.png",                        size: 15,                      ),                      const SizedBox(                        width: 5,                      ),                      Text("${widget.price}"),                    ])                  ]),            ),            const Expanded(              child: SizedBox(),            ),            TextButton(onPressed: used, child: Text("${widget.totalTimes}"))          ],        ),      )),    );*/    return badges.Badge(      position: badges.BadgePosition.topEnd(top: 2, end: 2),      badgeStyle: badges.BadgeStyle(        shape: badges.BadgeShape.circle,        badgeColor: Theme.of(context).primaryColor.withOpacity(0.6),        elevation: 0,      ),      badgeContent: SizedBox(        width: 20,        height: 20,        child: FittedBox(          child: Text("${widget.totalTimes}",            textAlign: TextAlign.center,          ),        ),      ),      child: GestureDetector(        onLongPress: widget.openEditPage,        onTap: used,        child: PrimaryContainer(          width: TileWithCounter.width,          height: 150, // Increase the height to provide more space          child: Column(            mainAxisSize: MainAxisSize.min,            mainAxisAlignment: MainAxisAlignment.spaceBetween,            children: [              const SizedBox(                height: 10,              ),              IconImage(                iconName: iconNames[widget.iconId],                size: 35,              ),              Padding(                padding:                    const EdgeInsets.symmetric(horizontal: 10, vertical: 2.5),                child: AutoSizeText(                  widget.name,                  maxLines: 2,                  textAlign: TextAlign.center,                  overflow: TextOverflow.ellipsis,                  minFontSize: 5,                  maxFontSize: 10,                ),              ),              Row(                mainAxisSize: MainAxisSize.max,                mainAxisAlignment: MainAxisAlignment.center,                children: [                  IconImage(                    iconName: "coin-front.png",                    size: 15,                  ),                  const SizedBox(                    width: 5,                  ),                  Text("${widget.price}",                    style: const TextStyle(fontSize: 12),                  ),                ],              ),              GestureDetector(                onTap: widget.openEditPage,                child: IconImage(iconName: "ellipsis-stroke.png", size: 15),              ),            ],          ),        ),      ),    );  }  @override  Widget build(BuildContext context) {    return isListView() ? listBuild() : gridBuild();  }}
habit.dartimport 'package:achivement_box/models/imageIcon.dart';import 'package:achivement_box/models/my_toast.dart';import 'package:achivement_box/output/generated/icon_names.dart';import 'package:achivement_box/pages/homePage/Bodies/HomeBody/provider/levelProvider.dart';import 'package:achivement_box/pages/homePage/Bodies/providers/coinsProvider.dart';import 'package:cherry_toast/resources/arrays.dart';import 'package:flutter/material.dart';import 'package:provider/provider.dart';import '../db/sql.dart';import '../pages/EditPages/editHabitPage.dart';import '../rootProvider/habitProvider.dart';import 'tileWithCounter.dart';class Habit extends TileWithCounter {  static const width = 110;  final bool isBadHabit;  final int priority;  final int hardness;  final int categoryId;  final int timeInMinutes;  void openEditPage() {    Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {      return EditHabitsPage(habit: this);    }));  }  @override  void clicked() {    if (super.totalTimes == 1) {      db.execute('''      insert into logHabit values('$formattedDate',${super.id},1)''');    } else {      db.execute('''      update  logHabit set      count = ${super.totalTimes}      where DateOnly = '$formattedDate'      and HabitId =${super.id}''');    }    if (isBadHabit) {      context.read<CoinsProvider>().removeCoins(super.price);    } else {      context.read<CoinsProvider>().addCoins(super.price);      context.read<LevelProvider>().xpIncreased();      toastTitle = "habit done";      undoToast.show(context);      int newLevel =          updateLevel(value: super.price + hardness + priority, id: categoryId);      if (newLevel != 0) {        MyToast(          title: const Text("Level up"),          animationType: AnimationType.fromBottom,          toastPosition: Position.bottom,          iconWidget: IconImage(            iconName: iconNames[getCategory(categoryId)['IconId']],          ),          displayCloseButton: true,        ).show(context);      }    }    context.read<HabitProvider>().habitUpdated();  }  @override  void undo() {    if (super.totalTimes == 1) {      db.execute('''      delete from logHabit where HabitId = ${super.id} and DateOnly = '$formattedDate'''');      super.totalTimes -= 1;    } else {      db.execute('''      update  logHabit set      count = ${--super.totalTimes}      where DateOnly = '$formattedDate'      and HabitId =${super.id}''');    }    context.read<HabitProvider>().habitUpdated();    if (isBadHabit) {      context.read<CoinsProvider>().addCoins(super.price);    } else {      context.read<CoinsProvider>().removeCoins(super.price);      context.read<LevelProvider>().xpIncreased();      removeLevel(value: super.price + hardness + priority, id: categoryId);    }  }  Habit({    required super.id,    required super.iconId,    required super.name,    required super.totalTimes,    required super.price,    required super.context,    required this.categoryId,    required this.isBadHabit,    required this.priority,    required this.hardness,    required this.timeInMinutes,  });}

Viewing all articles
Browse latest Browse all 611

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>