facing error in timer functionality in flutter project - flutter

*facing error in timer functionality in flutter project
*please any one can help me to get rid of this timer functionality error
import 'dart:async';
import 'package:flutter/material.dart';
class StopwatchHome extends StatefulWidget {
StopwatchHome({Key? key}) : super(key: key);
#override
State<StopwatchHome> createState() => _StopwatchHomeState();
}
class _StopwatchHomeState extends State<StopwatchHome> {
int secounds=0, minutes=0, hours=0;
String digitsecounds="00", digitminutes ="00", digithours="00";
Timer? timer;
bool started= false;
List laps=[];
void stop(){
timer!.cancel();
setState(() {
started=false;
});
}
void reset(){
timer!.cancel();
setState(() {
secounds=0;
minutes=0;
hours=0;
digitsecounds="00";
digitminutes="00";
digithours="00";
started=false;
});
}
void addlaps(){
String lap="$digithours:$digitminutes:$digitsecounds";
setState(() {
laps.add(lap);
});
}
void start(){
started=true;
timer=Timer.periodic(Duration(seconds: 1), (timer) {
int localSecounds=secounds+1;
int localMinutes= minutes=0;
int localHours= hours;
if (localSecounds>59) {
if (localMinutes>59) {
localHours++;
localMinutes==0;
}else{localMinutes++;localSecounds==0;}
}
setState(() {
secounds= localSecounds;
minutes= localMinutes;
hours= localHours;
digitsecounds=(secounds>=10)?"$secounds":"0$secounds";
digithours=(hours>=10)?"$hours":"0$hours";
digitminutes=(minutes>=10)?"$minutes":"0$minutes";
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor:
// const Color(0xff213a20),
Color.fromARGB(255, 138, 11, 87),
body: SafeArea(
child: Padding(
padding: EdgeInsets.all(18),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: Text("Stopwatch",
style: TextStyle(color: Colors.white,
fontWeight: FontWeight.bold,fontSize: 40,
fontStyle: FontStyle.italic),),
),
SizedBox(height: 20.0),
Center(child: Text("$digithours:$digitminutes:$digitsecounds",style: TextStyle(color: Colors.white,fontSize: 73.0,fontWeight: FontWeight.bold),),),
Container(
height: 300.0,
decoration: BoxDecoration(color: Color.fromARGB(255, 162, 109, 145),
borderRadius: BorderRadius.circular(10)),
child: ListView.builder(
itemCount: laps.length,
itemBuilder: (context,index){
return Padding(
padding: const EdgeInsets.all(18.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("Lap Number = ${index+1}",style: TextStyle(color: Colors.white,fontSize: 16 ),),
Text("${laps[index]}",style:TextStyle(color: Colors.white,fontSize: 16 ) )
],
),
);
}
),
),
SizedBox(height: 23),
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(child: RawMaterialButton(onPressed: (){
(!started) ? start():stop();
},
fillColor: Color.fromARGB(255, 73, 119, 4),
shape:StadiumBorder(side: BorderSide(color: Colors.blue)),
child: Text((! started)? "START":"PAUSE",style: TextStyle(color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic
),
),
)
),
SizedBox(width: 8),
IconButton(
onPressed: (){addlaps();}, icon: Icon(Icons.timelapse_rounded,color: Colors.red,)),
Expanded(child: RawMaterialButton(onPressed: (){reset();},
fillColor: Color.fromARGB(255, 132, 9, 23),
shape:StadiumBorder(side: BorderSide(color: Color.fromARGB(255, 40, 129, 11))),
child: Text("RESET",style: TextStyle(color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic
),
),
)
)
],
)
],
),
),
),
);
}
}
please any one can help me to get rid of this timer functionality error
#the digitsecound is not restarting after completing sixty secounds
#Anyone who can help? I'm definitely missing something.

The problem lies in this part:
else{localMinutes++;localSecounds==0;}
You are checking if localSecounds is equal to 0, not actually giving it the value 0(Same thing with minutes). Try:
if (localSecounds>59) {
if (localMinutes>59) {
localHours++;
localMinutes=0;
}else{
localMinutes++;
localSecounds=0;
}
}

Check this start Timer Function, it may help you out
late Timer _timer;
int seconds = 00;
int minutes = 00;
int hours = 00;
void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) => setState(
() {
seconds++;
if (seconds > 59) {
minutes += 1;
seconds = 0;
if (minutes > 59) {
hours += 1;
minutes = 0;
}
}
},
),
);
}

Or User can use this simple but powerful package : stop_watch_timer from pub.dev

Related

'(callback function) can`t be accessed in an initializer' Error

I am studying flutter while making a pomodoro app.
After setting this app to 25 minutes, press the middle button to decrease the time by seconds and press the button again to pause.
I am getting the following error while configuring the app using the Timer class.
The Timer class takes a repeating period and a callback function as arguments.
However, the 'tickDown' function receives the Timer class as an argument, but I don't know why the error pops up.
Below is the code I wrote. I'd like to hear your thoughts on what the problem is.
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
var totalSeconds = 1500;
Timer _timer = Timer.periodic(Duration(seconds: 1), tickDown);
bool isRunning = false;
void playTimer() {
setState(() {
isRunning = true;
_timer;
});
}
void pause() {
_timer.cancel();
setState(() {
isRunning = false;
});
}
void tickDown(Timer _timer) {
setState(() {
totalSeconds -= 1;
});
}
String showRemainTime() {
var hour = (totalSeconds ~/ 60).toString();
var minute = (totalSeconds % 60).toString();
String time;
minute.length == 1 ? time = '$hour : 0$minute' : time = '$hour : $minute';
return time;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
body: Column(
children: [
Flexible(
flex: 3,
fit: FlexFit.tight,
child: Container(
alignment: const Alignment(0, 0),
child: Text(
showRemainTime(),
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).cardColor,
fontSize: 80,
fontWeight: FontWeight.w700,
),
),
),
),
Flexible(
flex: 4,
fit: FlexFit.tight,
child: Container(
alignment: const Alignment(0, -0.5),
child: IconButton(
iconSize: 100,
padding: EdgeInsets.zero,
onPressed: isRunning == true ? pause : playTimer,
icon: Icon(
isRunning == true
? Icons.pause_circle_outline_rounded
: Icons.play_circle_outlined,
color: Theme.of(context).cardColor,
),
),
),
),
Flexible(
flex: 2,
fit: FlexFit.tight,
child: Container(
decoration: BoxDecoration(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
color: Theme.of(context).cardColor,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Pomodoro',
style: TextStyle(
fontSize: 23,
color: Theme.of(context).textTheme.headline1!.color,
fontWeight: FontWeight.w700,
),
),
Text(
'0',
style: TextStyle(
fontSize: 52,
color: Theme.of(context).textTheme.headline1!.color,
),
),
],
),
],
),
),
),
],
),
);
}
}
I also searched the flutter official documentation, but I couldn't find anything suitable for my situation. I want to fix this error with minimal modifications to my current code.
tickDown is a method of _HomeScreenState. Object methods cannot be accessed in initializers, because the object has not been fully constructed yet. This includes object properties with assignment definitions (like what you have) as well as initializers specified in constructors.
There are two ways you can overcome this.
Change your declaration of _timer to be late:
late var _timer = Timer.periodic(Duration(seconds: 1), tickDown);
However, for your particular situation, I don't recommend this approach.
Instantiate the timer later. This would look like
Timer? _timer;
void playTimer() {
setState(() {
_timer = Timer.periodic(Duration(seconds: 1), tickDown);
isRunning = true;
});
}
Note: To prevent issues, be sure to cancel the timer in the State's dispose() method.

How Can i create a conditional questionnaire in Flutter

I am trying to build a questionnaire within an application
The idea is that the user answers questions
So every answer he gives is in one question
Accordingly he will receive the following question
For example if he answered a question with answer a
Will get one question
If he answered the same question with answer b
Will get another question later
how can i solve this
The code is attached
Thanks
import 'package:flutter/material.dart';
import 'package:gsheets/question_model.dart';
class QuizScreen extends StatefulWidget {
#override
State<QuizScreen> createState() => _QuizScreenState();
}
class _QuizScreenState extends State<QuizScreen> {
//define the datas
List<Question> questionList = getQuestions();
int currentQuestionIndex = 0;
int score = 0;
Answer? selectedAnswer;
int? nextQuestionId;
int? questionId;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 5, 50, 80),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
child:
Column(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
const Text(
"Simple Quiz App",
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
_questionWidget(),
_answerList(),
_nextButton(),
]),
),
);
}
_questionWidget() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Question ${currentQuestionIndex + 1}/${questionList.length.toString()}",
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 20),
Container(
alignment: Alignment.center,
width: double.infinity,
padding: const EdgeInsets.all(32),
decoration: BoxDecoration(
color: Colors.orangeAccent,
borderRadius: BorderRadius.circular(16),
),
child: Text(
questionList[currentQuestionIndex].questionText,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
)
],
);
}
_answerList() {
return Column(
children: questionList[currentQuestionIndex]
.answerList
.map(
(e) => _answerButton(e),
)
.toList(),
);
}
Widget _answerButton(Answer answer) {
bool isSelected = answer == selectedAnswer;
return Container(
width: double.infinity,
margin: const EdgeInsets.symmetric(vertical: 8),
height: 48,
child: ElevatedButton(
child: Text(answer.answerText),
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
primary: isSelected ? Colors.orangeAccent : Colors.white,
onPrimary: isSelected ? Colors.white : Colors.black,
),
onPressed: () {
// if (selectedAnswer == null) {
// if (answer.isCorrect) {
// score++;
// }
setState(() {
selectedAnswer = answer;
});
}
// },
),
);
}
_nextButton() {
// if(answer == )
bool isLastQuestion = false;
if (currentQuestionIndex == questionList.length - 1) {
isLastQuestion = true;
}
return Container(
width: MediaQuery.of(context).size.width * 0.5,
height: 48,
child: ElevatedButton(
child: Text(isLastQuestion ? "Submit" : "Next"),
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
primary: Colors.blueAccent,
onPrimary: Colors.white,
),
onPressed: () {
// if(nextQuestionId == questionId)
if (isLastQuestion) {
//display score
showDialog(context: context, builder: (_) => _showScoreDialog());
} else {
//next question
setState(() {
selectedAnswer = null;
currentQuestionIndex++;
});
}
},
),
);
}
_showScoreDialog() {
bool isPassed = false;
if (score >= questionList.length * 0.6) {
//pass if 60 %
isPassed = true;
}
String title = isPassed ? "Passed " : "Failed";
return AlertDialog(
title: Text(
title + " | Score is $score",
style: TextStyle(color: isPassed ? Colors.green : Colors.redAccent),
),
content: ElevatedButton(
child: const Text("Restart"),
onPressed: () {
Navigator.pop(context);
setState(() {
currentQuestionIndex = 0;
score = 0;
selectedAnswer = null;
});
},
),
);
}
}
========================
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gsheets/quiz.dart';
class Question {
final String questionText;
final List<Answer> answerList;
final int questionId;
Question(this.questionText, this.answerList, this.questionId);
}
class Answer {
final String answerText;
final int nextQuestionId;
// final bool selectedOption;
Answer(this.answerText, this.nextQuestionId);
}
List<Question> getQuestions() {
List<Question> list = [];
list.add(Question(
"Which school did you learn",
[
Answer("a", 3),
Answer("b", 2),
],
3,
));
list.add(Question(
"what is your age",
[
Answer("18", 3),
Answer("20", 5),
],
2,
));
list.add(Question(
"which car do you drive",
[
Answer("c", 3),
Answer("d", 2),
],
3,
));
return list;
}

Unsupported operation: Cannot add to an unmodifiable list

I have an app that has a splash screen and an onboarding screen. There are no errors or warnings anywhere; the app runs to show the splash screen but then crashes instead of displaying the onboarding screen.
======== Exception caught by widgets library =======================================================
The following UnsupportedError was thrown building BoardingPage(dirty, state: _BoardingScreenState#e3368):
Unsupported operation: Cannot add to an unmodifiable list
The relevant error-causing widget was:
BoardingPage BoardingPage:file:///C:/Users/Srishti/AndroidStudioProjects/App-mini-project-1/lib/splash.dart:22:78
Here's my code :
splash.dart
import 'package:flutter/material.dart';
import 'boarding_screen.dart';
class Splash extends StatefulWidget {
const Splash({Key? key}) : super(key: key);
#override
State<Splash> createState() => _SplashState();
}
class _SplashState extends State<Splash> {
#override
void initState(){
super.initState();
_navigatetohome();
}
_navigatetohome() async {
await Future.delayed(Duration(milliseconds: 2500), (){});
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => BoardingPage()));
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: Text('Your Scheduler',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.normal,
),
),
),
),
);
}
}
slide.dart
class Slide {
String image;
String heading;
Slide(this.image, this.heading);
}
boarding_screen.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gradient_widgets/gradient_widgets.dart';
import 'package:schedule_management/slide.dart';
import 'login_screen.dart';
class BoardingPage extends StatefulWidget {
const BoardingPage({Key? key}) : super(key: key);
#override
_BoardingScreenState createState() => _BoardingScreenState();
}
class _BoardingScreenState extends State<BoardingPage> {
int _currentPage = 0;
List<Slide> _slides = [];
PageController _pageController = PageController();
#override
void initState() {
_currentPage = 0;
_slides = [
Slide("images/slide-1.png", "Manage your time"),
Slide("images/slide-2.png", "Schedule your tasks"),
Slide("images/slide-3.png", "Never miss out on any task"),
];
_pageController = PageController(initialPage: _currentPage);
super.initState();
}
// the list which contain the build slides
List<Widget> _buildSlides() {
return _slides.map(_buildSlide).toList();
}
// building single slide
Widget _buildSlide(Slide slide) {
return Column(
children: <Widget>[
Expanded(
child: Container(
margin: const EdgeInsets.all(1),
child: Image.asset(slide.image, fit: BoxFit.contain),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 70),
child: Text(
slide.heading,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.w900,
),
),
),
const SizedBox(
height: 230,
)
],
);
}
// handling the on page changed
void _handlingOnPageChanged(int page) {
setState(() => _currentPage = page);
}
// building page indicator
Widget _buildPageIndicator() {
Row row = Row(mainAxisAlignment: MainAxisAlignment.center, children: const []);
for (int i = 0; i < _slides.length; i++) {
row.children.add(_buildPageIndicatorItem(i));
if (i != _slides.length - 1) {
row.children.add(const SizedBox(
width: 12,
));
}
}
return row;
}
Widget _buildPageIndicatorItem(int index) {
return Container(
width: index == _currentPage ? 8 : 5,
height: index == _currentPage ? 8 : 5,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: index == _currentPage
? const Color.fromRGBO(136, 144, 178, 1)
: const Color.fromRGBO(206, 209, 223, 1)),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Stack(
children: <Widget>[
PageView(
controller: _pageController,
onPageChanged: _handlingOnPageChanged,
physics: BouncingScrollPhysics(),
children: _buildSlides(),
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Column(
children: <Widget>[
_buildPageIndicator(),
SizedBox(height: 32,),
Container(
// see the page indicators
margin: EdgeInsets.symmetric(horizontal: 10000000),
child: SizedBox(
width: double.infinity,
child: GradientButton(
callback: () => {},
gradient: LinearGradient(colors: const [
Color.fromRGBO(11, 198, 200, 1),
Color.fromRGBO(68, 183, 183, 1)
]),
elevation: 0,
increaseHeightBy: 28,
increaseWidthBy: double.infinity,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100),
),
child: Text(
"",
style: TextStyle(
letterSpacing: 4,
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
)),
),
SizedBox(height: 10,),
CupertinoButton(
child: Text(
"Sign In",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: Colors.grey,
),
),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => LoginScreen()));
}),
SizedBox(height: 30,),
],
),
)
],
),
);
}
}
I have tried restarting Android Studio and running flutter clean but the app still crashes.
The problem probably because of the following code:
Widget _buildPageIndicator() {
Row row = Row(mainAxisAlignment: MainAxisAlignment.center, children: const []);
for (int i = 0; i < _slides.length; i++) {
row.children.add(_buildPageIndicatorItem(i));
if (i != _slides.length - 1) {
row.children.add(const SizedBox(
width: 12,
));
}
}
return row;
}
where you're trying to change the const row children. So, change it like the following code:
Widget _buildPageIndicator() {
List<Widget> children = [];
for (int i = 0; i < _slides.length; i++) {
children.add(_buildPageIndicatorItem(i));
if (i != _slides.length - 1) {
children.add(const SizedBox(
width: 12,
));
}
}
return Row(mainAxisAlignment: MainAxisAlignment.center,
children: children,
);
}

Null check operator used on a null value Carousel Flutter

Good Morning,
I'm trying to put a Carousel on the home page looking for Firebase data, but for some reason, the first time I load the application it appears the message below:
════════ Exception caught by widgets library ═════════════════════════════════════ ══════════════════
The following _CastError was thrown building DotsIndicator (animation: PageController # 734f9 (one client, offset 0.0), dirty, state: _AnimatedState # 636ca):
Null check operator used on a null value
and the screen looks like this:
After giving a hot reload the error continues to appear, but the image is loaded successfully, any tips of what I can do?
HomeManager:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provantagens_app/models/section.dart';
class HomeManager extends ChangeNotifier{
HomeManager({this.images}){
_loadSections();
images = images ?? [];
}
void addSection(Section section){
_editingSections.add(section);
notifyListeners();
}
final List<dynamic> _sections = [];
List<String> images;
List<dynamic> newImages;
List<dynamic> _editingSections = [];
bool editing = false;
bool loading = false;
int index, totalItems;
final Firestore firestore = Firestore.instance;
Future<void> _loadSections() async{
loading = true;
firestore.collection('home').snapshots().listen((snapshot){
_sections.clear();
for(final DocumentSnapshot document in snapshot.documents){
_sections.add( Section.fromDocument(document));
images = List<String>.from(document.data['images'] as List<dynamic>);
}
});
loading = false;
notifyListeners();
}
List<dynamic> get sections {
if(editing)
return _editingSections;
else
return _sections;
}
void enterEditing({Section section}){
editing = true;
_editingSections = _sections.map((s) => s.clone()).toList();
defineIndex(section: section);
notifyListeners();
}
void saveEditing() async{
bool valid = true;
for(final section in _editingSections){
if(!section.valid()) valid = false;
}
if(!valid) return;
loading = true;
notifyListeners();
for(final section in _editingSections){
await section.save();
}
for(final section in List.from(_sections)){
if(!_editingSections.any((s) => s.id == section.id)){
await section.delete();
}
}
loading = false;
editing = false;
notifyListeners();
}
void discardEditing(){
editing = false;
notifyListeners();
}
void removeSection(Section section){
_editingSections.remove(section);
notifyListeners();
}
void onMoveUp(Section section){
int index = _editingSections.indexOf(section);
if(index != 0) {
_editingSections.remove(section);
_editingSections.insert(index - 1, section);
index = _editingSections.indexOf(section);
}
notifyListeners();
}
HomeManager clone(){
return HomeManager(
images: List.from(images),
);
}
void onMoveDown(Section section){
index = _editingSections.indexOf(section);
totalItems = _editingSections.length;
if(index < totalItems - 1){
_editingSections.remove(section);
_editingSections.insert(index + 1, section);
index = _editingSections.indexOf(section);
}else{
}
notifyListeners();
}
void defineIndex({Section section}){
index = _editingSections.indexOf(section);
totalItems = _editingSections.length;
notifyListeners();
}
}
HomeScreen:
import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';
import 'package:provantagens_app/commom/custom_drawer.dart';
import 'package:provantagens_app/commom/custom_icons_icons.dart';
import 'package:provantagens_app/models/home_manager.dart';
import 'package:provantagens_app/models/section.dart';
import 'package:provantagens_app/screens/home/components/home_carousel.dart';
import 'package:provantagens_app/screens/home/components/menu_icon_tile.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
// ignore: must_be_immutable
class HomeScreen extends StatelessWidget {
HomeManager homeManager;
Section section;
List<Widget> get children => null;
String videoUrl = 'https://www.youtube.com/watch?v=VFnDo3JUzjs';
int index;
var _tapPosition;
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(colors: const [
Colors.white,
Colors.white,
], begin: Alignment.topCenter, end: Alignment.bottomCenter)),
child: Scaffold(
backgroundColor: Colors.transparent,
drawer: CustomDrawer(),
appBar: AppBar(
backgroundColor: Colors.transparent,
iconTheme: IconThemeData(color: Colors.black),
title: Text('Página inicial', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8))),
centerTitle: true,
actions: <Widget>[
Divider(),
],
),
body: Consumer<HomeManager>(
builder: (_, homeManager, __){
return ListView(children: <Widget>[
AspectRatio(
aspectRatio: 1,
child:HomeCarousel(homeManager),
),
Column(
children: <Widget>[
Container(
height: 50,
),
Divider(
color: Colors.black,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.only(left:12.0),
child: MenuIconTile(title: 'Parceiros', iconData: Icons.apartment, page: 1,),
),
Padding(
padding: const EdgeInsets.only(left:7.0),
child: MenuIconTile(title: 'Beneficios', iconData: Icons.card_giftcard, page: 2,),
),
Padding(
padding: const EdgeInsets.only(right:3.0),
child: MenuIconTile(title: 'Suporte', iconData: Icons.help_outline, page: 6,),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
MenuIconTile(iconData: Icons.assignment,
title: 'Dados pessoais',
page: 3)
,
MenuIconTile(iconData: Icons.credit_card_outlined,
title: 'Meu cartão',
page: 4)
,
MenuIconTile(iconData: Icons.account_balance_wallet_outlined,
title: 'Pagamento',
page: 5,)
,
],
),
Divider(
color: Colors.black,
),
Container(
height: 50,
),
Consumer<HomeManager>(
builder: (_, sec, __){
return RaisedButton(
child: Text('Teste'),
onPressed: (){
Navigator.of(context)
.pushReplacementNamed('/teste',
arguments: sec);
},
);
},
),
Text('Saiba onde usar o seu', style: TextStyle(color: Colors.black, fontSize: 20),),
Text('Cartão Pró Vantagens', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8), fontSize: 30),),
AspectRatio(
aspectRatio: 1,
child: Image.network(
'https://static.wixstatic.com/media/d170e1_80b5f6510f5841c19046f1ed5bca71e4~mv2.png/v1/fill/w_745,h_595,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es.webp',
fit: BoxFit.fill,
),
),
Divider(),
Container(
height: 150,
child: Row(
children: [
AspectRatio(
aspectRatio: 1,
child: Image.network(
'https://static.wixstatic.com/media/d170e1_486dd638987b4ef48d12a4bafee20e80~mv2.png/v1/fill/w_684,h_547,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es_2.webp',
fit: BoxFit.fill,
),
),
Padding(
padding: const EdgeInsets.only(left:20.0),
child: RichText(
text: TextSpan(children: <TextSpan>[
TextSpan(
text: 'Adquira já o seu',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
TextSpan(
text: '\n\CARTÃO PRÓ VANTAGENS',
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 30, 158, 8)),
),
]),
),
),
],
),
),
Divider(),
tableBeneficios(),
Divider(),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Text(
'O cartão Pró-Vantagens é sediado na cidade de Hortolândia/SP e já está no mercado há mais de 3 anos. Somos um time de profissionais apaixonados por gestão de benefícios e empenhados em gerar o máximo de valor para os conveniados.'),
FlatButton(
onPressed: () {
launch(
'https://www.youtube.com/watch?v=VFnDo3JUzjs');
},
child: Text('SAIBA MAIS')),
],
),
),
Container(
color: Color.fromARGB(255, 105, 190, 90),
child: Column(
children: <Widget>[
Row(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'© 2020 todos os direitos reservados a Cartão Pró Vantagens.',
style: TextStyle(fontSize: 10),
),
)
],
),
Divider(),
Row(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Rua Luís Camilo de Camargo, 175 -\n\Centro, Hortolândia (piso superior)',
style: TextStyle(fontSize: 10),
),
),
Padding(
padding: const EdgeInsets.only(left: 16),
child: IconButton(
icon: Icon(CustomIcons.facebook),
color: Colors.black,
onPressed: () {
launch(
'https://www.facebook.com/provantagens/');
},
),
),
Padding(
padding: const EdgeInsets.only(left: 16),
child: IconButton(
icon: Icon(CustomIcons.instagram),
color: Colors.black,
onPressed: () {
launch(
'https://www.instagram.com/cartaoprovantagens/');
},
),
),
],
),
],
),
)
],
),
]);
},
)
),
);
}
tableBeneficios() {
return Table(
defaultColumnWidth: FlexColumnWidth(120.0),
border: TableBorder(
horizontalInside: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.0,
),
verticalInside: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.0,
),
),
children: [
_criarTituloTable(",Plus, Premium"),
_criarLinhaTable("Seguro de vida\n\(Morte Acidental),X,X"),
_criarLinhaTable("Seguro de Vida\n\(Qualquer natureza),,X"),
_criarLinhaTable("Invalidez Total e Parcial,X,X"),
_criarLinhaTable("Assistência Residencial,X,X"),
_criarLinhaTable("Assistência Funeral,X,X"),
_criarLinhaTable("Assistência Pet,X,X"),
_criarLinhaTable("Assistência Natalidade,X,X"),
_criarLinhaTable("Assistência Eletroassist,X,X"),
_criarLinhaTable("Assistência Alimentação,X,X"),
_criarLinhaTable("Descontos em Parceiros,X,X"),
],
);
}
_criarLinhaTable(String listaNomes) {
return TableRow(
children: listaNomes.split(',').map((name) {
return Container(
alignment: Alignment.center,
child: RichText(
text: TextSpan(children: <TextSpan>[
TextSpan(
text: name != "X" ? '' : 'X',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
TextSpan(
text: name != 'X' ? name : '',
style: TextStyle(
fontSize: 10.0,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 30, 158, 8)),
),
]),
),
padding: EdgeInsets.all(8.0),
);
}).toList(),
);
}
_criarTituloTable(String listaNomes) {
return TableRow(
children: listaNomes.split(',').map((name) {
return Container(
alignment: Alignment.center,
child: RichText(
text: TextSpan(children: <TextSpan>[
TextSpan(
text: name == "" ? '' : 'Plano ',
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
TextSpan(
text: name,
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 30, 158, 8)),
),
]),
),
padding: EdgeInsets.all(8.0),
);
}).toList(),
);
}
void _storePosition(TapDownDetails details) {
_tapPosition = details.globalPosition;
}
}
I forked the library to create a custom carousel for my company's project, and since we updated flutter to 2.x we had the same problem.
To fix this just update boolean expressions like
if(carouselState.pageController.position.minScrollExtent == null ||
carouselState.pageController.position.maxScrollExtent == null){ ... }
to
if(!carouselState.pageController.position.hasContentDimensions){ ... }
Here is flutter's github reference.
This worked for me
So I edited scrollposition.dart package
from line 133
#override
//double get minScrollExtent => _minScrollExtent!;
// double? _minScrollExtent;
double get minScrollExtent {
if (_minScrollExtent == null) {
_minScrollExtent = 0.0;
}
return double.parse(_minScrollExtent.toString());
}
double? _minScrollExtent;
#override
// double get maxScrollExtent => _maxScrollExtent!;
// double? _maxScrollExtent;
double get maxScrollExtent {
if (_maxScrollExtent == null) {
_maxScrollExtent = 0.0;
}
return double.parse(_maxScrollExtent.toString());
}
double? _maxScrollExtent;
Just upgrade to ^3.0.0 Check here https://pub.dev/packages/carousel_slider
I faced the same issue.
This is how I solved it
class PlansPage extends StatefulWidget {
const PlansPage({Key? key}) : super(key: key);
#override
State<PlansPage> createState() => _PlansPageState();
}
class _PlansPageState extends State<PlansPage> {
int _currentPage = 1;
late CarouselController carouselController;
#override
void initState() {
super.initState();
carouselController = CarouselController();
}
}
Then put initialization the carouselController inside the initState method I was able to use the methods jumpToPage(_currentPage ) and animateToPage(_currentPage) etc.
I use animateToPage inside GestureDetector in onTap.
onTap: () {
setState(() {
_currentPage = pageIndex;
});
carouselController.animateToPage(_currentPage);
},
I apologize in advance if this is inappropriate.
I solved the similar problem as follows. You can take advantage of the Boolean variable. I hope, help you.
child: !loading ? HomeCarousel(homeManager) : Center(child:ProgressIndicator()),
or
child: isLoading ? HomeCarousel(homeManager) : SplashScreen(),
class SplashScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Loading...')
),
);
}
}

Flutter: The Method was called on null

I want to run my App,but im getting this error after I tried to reload
it. But i keep getting this error. I tried to remove some code that i
edited befor it stopped working but i keep getting this error. This Code is from the following link and i changed it a bit. "https://pub.dev/packages/flutter_circular_slider" Cansomeone help me?
error Message
My Error Message in the Terminal:
The method '>' was called on null. Receiver: null Tried calling: >(null)
class Register extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: RegisterLayout(),
);
}
}
class RegisterLayout extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: RegisterPage(),
),
);
}
}
class RegisterPage extends StatefulWidget {
#override
_RegisterThirdPageState createState() => _RegisterThirdPageState();
}
class _RegisterThirdPageState extends State<RegisterPage> {
int initTime;
int endTime;
int inBedTime;
int outBedTime;
String startReading;
String endReading;
String overTime;
#override
void _updateLabels(int init, int end, int all) {
setState(() {
inBedTime = init;
outBedTime = end;
});
}
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(height: 20),
Text(
'How long did you want to read',
style: TextStyle(color: Colors.green[600], fontSize: 22),
),
DoubleCircularSlider(
288,
initTime,
endTime,
height: 300.0,
width: 300.0,
primarySectors: 4,
baseColor: Colors.grey[200],
selectionColor: Colors.green[400],
handlerColor: Colors.green[600],
handlerOutterRadius: 20.0,
onSelectionChange: _updateLabels,
sliderStrokeWidth: 40.0,
child: Padding(
padding: const EdgeInsets.all(42.0),
child: Center(
child: Text('${_formatIntervalTime(inBedTime, outBedTime)}',
style: TextStyle(fontSize: 40.0, color: Colors.green[600]))),
),
),
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
_formatBedTime('START', inBedTime),
_formatBedTime('END', outBedTime),
]),
FlatButton(
padding: EdgeInsets.only(top: 10, bottom: 10, left: 100, right: 100),
child: Text('N E X T', style: TextStyle(fontSize: 30),),
color: Colors.green[400],
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
onPressed: () {
startReading = _formatTime(inBedTime);
endReading = _formatTime(outBedTime);
overTime = _formatIntervalTime(inBedTime, outBedTime);
print(startReading);
print(endReading);
print(overTime);
},
),
],
);
}
Widget _formatBedTime(String pre, int time) {
return Column(
children: [
Text(pre, style: TextStyle(color: Colors.green[400], fontSize: 16)),
Text('READING AT', style: TextStyle(color: Colors.green[400], fontSize: 16)),
Text(
'${_formatTime(time)}',
style: TextStyle(color: Colors.green[600], fontSize: 24),
)
],
);
}
String _formatTime(int time) {
if (time == 0 || time == null) {
return '00:00';
}
var hours = time ~/ 12;
var minutes = (time % 12) * 5;
return '$hours:$minutes';
}
String _formatIntervalTime(int init, int end) {
var sleepTime = end > init ? end - init : 288 - init + end;
var hours = sleepTime ~/ 12;
var minutes = (sleepTime % 12) * 5;
return '${hours}h${minutes}m';
}
int _generateRandomTime() => Random().nextInt(288);
}