In my code I will use Provider.value to expose a value to MyHomePage ,at the same time ,the MyHomePage will use Provider to get the value with the listen set to true,If i change the value outside , the MyHomePage will not rebuild , seems the listenning not working .
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
int _counter = 0;
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Provider.value(
value: _counter,
child: MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
void _incrementCounter() {
_counter++;
}
@override
Widget build(BuildContext context) {
print('build');
int value = Provider.of<int>(
context,
listen: true,
);
return Scaffold(
appBar: AppBar(
title: Text('123'),
),
body: Center(
child: Text('value:${value}'),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
You need to use a model that would notify its listeners if you want your widgets to rebuild.
Providerhas no way to know you incremented_counted.Do those code changes to use
ValueNotifier<int>instead ofint(you will also need to replaceProviderwithChangeNotifierProvider):It would be better to not use a static global variable and
ChangeNotifierProvider.valuebutChangeNotifierProvider.newinstead.