I am learning about provider package in which I created an app in which whatever I type in the TextField will change the title in the appbar and a text Widget below TextField. but it was not working so I started trying different codes and after some tries it started working when I changed the listen to false in the TextField onchanged.
I still don't understand why it started working after setting listen: false.
TextField(
onChanged: (newValue) {
Provider.of<Data>(context, listen: false).changeString(newValue);
},
);
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider<Data>(create: (context) => Data()),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FirstPage(),
);
}
}
class FirstPage extends StatelessWidget {
const FirstPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(
child: MyText(),
),
),
body: Level1(),
);
}
}
class Level1 extends StatelessWidget {
const Level1({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Level2(),
);
}
}
class Level2 extends StatelessWidget {
const Level2({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
MyTextField(),
Level3(),
],
);
}
}
class Level3 extends StatelessWidget {
const Level3({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(Provider.of<Data>(context).data);
}
}
class MyText extends StatelessWidget {
const MyText({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(Provider.of<Data>(context).data);
}
}
class MyTextField extends StatelessWidget {
const MyTextField({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextField(
onChanged: (newValue) {
Provider.of<Data>(context, listen: false).changeString(newValue);
},
);
}
}
class Data extends ChangeNotifier {
String data = 'My Data';
void changeString(String newString) {
data = newString;
notifyListeners();
}
}