I am trying to increase counter when app call init and using provider to change the state of counter but getting this error i don't understand why i have made the listen to false but no solved kindly help
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:providerpractice/counter.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int count = 0;
Timer? timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 1), (timer) {
var pro = Provider.of<Counter>(context, listen: false);
pro.addCounter();
});
}
@override
Widget build(BuildContext context) {
print("build" count.toString());
return Scaffold(
appBar: AppBar(
title: Text("Provider State Management"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Consumer<Counter>(builder: ((context, value, child) {
return Text(
value.counter.toString(),
style: TextStyle(fontSize: 30),
);
}))
],
),
),
);
}
}
CodePudding user response:
If I am not mistaken, you can't use "context" in the initState method, rather move it out of there put it in a didChangeDependancy method.
I am sure someone can elaborate more on this, but the widget has no context until after the initState.
CodePudding user response:
I think the error you're getting is a result of the fact that you do not have any logic to dispose of your active work. Try implementing something in onDispose(). You could also elaborate more on the error you're getting. There is no mention of the error type or statement in your question.