Aditya Komawar
Aditya Komawar

Reputation: 71

I am using notifyListner from flutter Provider package but my UI is not updating

I am using notifyListner from flutter Provider package but my UI is not updating whenever I am typing the letters in the TextField. I am making this app just to understand how Provider works. My appbar and text is supposed to change whenever I type the text in TextFiled. Here's my code,

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Data>(
      create: (context) => Data(),
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: MyAppBar(),
          ),
          body: SafeArea(
            child: Column(
              children: [
                MyTextField(),
                Expanded(
                  child: MyTextWidget(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class MyTextField extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextField(
        onChanged: (newValue) {
          Provider.of<Data>(context, listen: true).changeString(newValue);
        },
      ),
    );
  }
}

class MyTextWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(Provider.of<Data>(context, listen: true).appName),
    );
  }
}

class MyAppBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(Provider.of<Data>(context, listen: true).appName);
  }
}

class Data extends ChangeNotifier {
  String appName = 'Understanding Provider';

  void changeString(String newString) {
    appName = newString;
    notifyListeners();
  }
}

Please somebody help, Thanks!

Upvotes: 0

Views: 180

Answers (1)

Thierry
Thierry

Reputation: 8393

You should not listen to your provider when you update it inside MyTextField:

class MyTextField extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextField(
        onChanged: (newValue) {
          Provider.of<Data>(context, listen: false).changeString(newValue);
        },
      ),
    );
  }
}

Set listen: false.

Upvotes: 1

Related Questions