Home > OS >  Provider doesn't update class data
Provider doesn't update class data

Time:05-10

P is an class to save user information.

class P extends ChangeNotifier(){
    String? username;
    void upd(String str){
        userName = str;
        notifyListener();
    }
}

Updating data by doing;

context.read<P>().upd("Hi");

However, the next code returns only null

context.read<P>().username;

main() was called with MultiProvider.

runApp(MultiProvider(
    providers: [
      ListenableProvider(create: (context) => P()),
         ........

Why username isn't updated?

CodePudding user response:

Use context.watch<T>(), which makes the widget listen to changes on T.

CodePudding user response:

As @user18309290 said, just complementing with a more complete code.

If you want to, you can try it on https://dartpad.dev/ (Just push the FloatingActionButton once at least.

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

void main() => runApp(
  MultiProvider(
    providers: [ListenableProvider(create: (_) => P())],
    child: MyApp(),
  )
);

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Test',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Test'),
      ),
      body: Center(
        child: Text(context.watch<P>().userName ?? 'Null username'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (context.read<P>().userName != 'Teste 1') {
            context.read<P>().upd('Teste 1');
          } else {
            context.read<P>().upd('Teste 2');
          }
        },
      ),
    );
  }
}

class P extends ChangeNotifier {
    String? userName;
    void upd(String str){
        userName = str;
        notifyListeners();
    }
}
  • Related