这里我有颤振提供者的代码
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
.
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;
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;
},
),
),
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),
),
);
}
}