Метод updateShouldNotify
Метод updateShouldNotify виджета InheritedWidget сравнивает новый виджет со старым и возвращает true, если зависимые элементы нужно перестроить. Flutter вызывает его при замене InheritedWidget с тем же типом и key.
Синтаксис
@override
bool updateShouldNotify(covariant OldWidget oldWidget)
Параметры
| Параметр | Описание |
|---|---|
oldWidget |
Предыдущий экземпляр того же InheritedWidget.
Сравнивают поля с текущим виджетом.
|
Пример
Давайте вернём true, когда меняется label:
import 'package:flutter/material.dart';
void main()
{
runApp(const MaterialApp(home: NotifyDemo()));
}
class NotifyDemo extends StatefulWidget
{
const NotifyDemo({super.key});
@override
State<NotifyDemo> createState() => _NotifyDemoState();
}
class _NotifyDemoState extends State<NotifyDemo>
{
var label = 'abcde';
@override
Widget build(BuildContext context)
{
return CountScope(
label: label,
child: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CountView(),
ElevatedButton(
onPressed: () => setState(() => label = '12345'),
child: const Text('go'),
),
],
),
),
),
);
}
}
class CountScope extends InheritedWidget
{
const CountScope({super.key, required this.label, required super.child});
final String label;
@override
bool updateShouldNotify(CountScope oldWidget) => label != oldWidget.label;
static CountScope? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<CountScope>();
}
}
class CountView extends StatelessWidget
{
const CountView({super.key});
@override
Widget build(BuildContext context)
{
return Text(CountScope.of(context)?.label ?? 'empty');
}
}
На экране updateShouldNotify обновит текст на '12345' после кнопки go.
Пример
Давайте выведем результат updateShouldNotify в консоль:
import 'package:flutter/material.dart';
void main()
{
const a = FlagScope(on: false, child: SizedBox.shrink());
const b = FlagScope(on: true, child: SizedBox.shrink());
print(a.updateShouldNotify(b));
}
class FlagScope extends InheritedWidget
{
const FlagScope({super.key, required this.on, required super.child});
final bool on;
@override
bool updateShouldNotify(FlagScope oldWidget) => on != oldWidget.on;
}
Результат выполнения кода
true
Смотрите также
-
виджет
InheritedWidget,
к которому относитсяupdateShouldNotify -
метод
updateShouldNotifyDependent,
который фильтрует потомков по аспекту -
метод
didChangeDependencies,
который вызывают уStateпри уведомлении -
метод
dependOnInheritedWidgetOfExactType,
который регистрирует зависимых