Riverpod hooks_riverpod HookWidget

hsuan-ming Yang
1 min readJun 14, 2022

HookConsumerWidget 允許同時使用Provider和Hooks

// 使用 HookConsumerWidget
class MyConsumerApp extends HookConsumerWidget {
const MyConsumerApp({
Key? key,
}) : super(key: key);

@override
Widget build(BuildContext context, WidgetRef ref) {
// 必須在 build 內宣告
final state = useState(0);
//
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("My Consumer App"),),
body: Center(
child: Text("${state.value}",
style: const TextStyle(fontSize: 30),
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
state.value++;
},
child: Icon(Icons.add),),
),
);
}
}

StatefulHookConsumerWidget:需要使用StatefulWidget生命週期時

class MyStatefulConsumerWidget extends StatefulHookConsumerWidget {
const MyStatefulConsumerWidget({Key? key}) : super(key: key);

@override
MyStatefulConsumerWidgetState createState() => MyStatefulConsumerWidgetState();
}

class MyStatefulConsumerWidgetState extends ConsumerState<MyStatefulConsumerWidget> {

@override
void initState() {
super.initState();
// "ref" 可以在StatefulWidget的生命週期使用
ref.read(stateProvider);
}

@override
Widget build(BuildContext context) {
// 必須在 build 內宣告
final state = useState(0);
//
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("My Consumer App"),),
body: Center(
child: Text("${state.value}",
style: const TextStyle(fontSize: 30),
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
state.value++;
},
child: Icon(Icons.add),),
),
);
}
}

HookConsumer / Consumer

final stateProvider = StateProvider<int>((ref) => 0);
...
class
MyHomePage extends ConsumerWidget {
const MyHomePage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(
title: const Text("Consumer Widget")
),
body: const Center(
child: MyTextWidget(),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.plus_one),
onPressed: (){
ref.read(stateProvider.notifier).state++;
},
),
);
}
}
// 封裝Widget 測試Consumer
class MyTextWidget extends StatelessWidget {
const MyTextWidget({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Consumer(builder: (context, ref , child){
final value = ref.watch(stateProvider);
return Text("${value}", style: const TextStyle(fontSize: 30),);
});
}
}

關鍵字

StateProvider、HookConsumerWidget、StatefulHookConsumerWidget

--

--