这里我有 Flutter 提供程序类 Page 的代码,扩展了 StatelessWidget { GlobalState? _state; GlobalState get state => _state!; set state(GlobalState value) => _state ??= value; Wi...
这里我有 Flutter 提供程序的代码
class Page extends StatelessWidget {
GlobalState? _state;
GlobalState get state => _state!;
set state(GlobalState value) => _state ??= value;
Widget build(BuildContext context) {
state = context.read<GlobalState>();
return Selector<GlobalState, int> (
selector: (_, innerState) => innerState.intValue,
builder: (_, value, child) => ...
);
}
}
我确信状态将在首次构建时初始化,下次程序将发现状态不为空并且不会匹配 context.read<GlobalState>
,但是在 Selector
,每次当状态时 notifyListener
, Selector
总会再次寻找相同的 GlobalState
,我该如何改进我的代码?
我认为我已经找到了 的位置 GlobalState
,因此无需 GlobalState
再次寻找 ,我不知道如何在 中修复它 Provider
,或者我应该转向 getx
?
这是 ChangeNotifier
您的案例的示例。您可以划分小的Widget并直接返回 Selector
如果您不想在状态更改时更新小部件,则 shouldRebuild
可以使用 Selector
。
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => Counter()),
],
child: const MyApp(),
),
);
}
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
/// This function only use when you need change state,
/// but doesn't want to re-render all widget that get this state
// void increment(bool isNotify) {
// _count++;
// if (isNotify) {
// notifyListeners();
// }
// }
void increment() {
_count++;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Center(
child: Selector<Counter, int>(
builder: (context, data, child) {
return Container(
height: 40,
color: Colors.red,
child: Center(child: Text('Consumer1: $data')),
);
},
selector: (buildContext, state) {
return state.count;
},
shouldRebuild: (prevState, nextState) {
//Change logic update widget when state change at here.
// Return false when widget only get state once time.
return false;
}
),
),
floatingActionButton: FloatingActionButton(
key: const Key('increment_floatingActionButton'),
/// Calls `context.read` instead of `context.watch` so that it does not rebuild
/// when [Counter] changes.
onPressed: () => context.read<Counter>().increment(),
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}