Read Data with ConsumerStatefulWidget in Riverpod
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// Create Provider
final nameProvider = Provider<String>((ref){
return 'Hello Avi';
});
void main(){
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Riverpod',
debugShowCheckedModeBanner: false,
home: const MyHomePage(),
);
}
}
// Create ConsumerStatefulWidget
class MyHomePage extends ConsumerStatefulWidget{
const MyHomePage({Key? key}): super(key: key);
@override
_MyHomePage createState()=> _MyHomePage();
}
class _MyHomePage extends ConsumerState<MyHomePage>{
@override
// Create initState
void initState(){
super.initState();
final name=ref.read(nameProvider);
print(name);
}
@override
Widget build(BuildContext context){
// Create Instance of Provider
final name=ref.watch(nameProvider);
final name=ref.watch(nameProvider);
return Scaffold(
appBar: AppBar(
title: Text("Riverpod Stateful Widget"),
backgroundColor: Colors.pink,
),
body: SafeArea(
child: Column(
children: [
Text("Welcome"),
// Call Provider
Text (name),
],
),
),
);
}
}
Text (name),
],
),
),
);
}
}
No comments:
Post a Comment