Flutter Stateful widget - Part3 - InheritedWidget Example - Sample Post List
Last updated Jan 04, 2020Hello Guys in previous post we discussed Statefull widget and How to access state of widget.
In this post i am going to show you how to handle state with InheritedWidget
In this Example we are going to create posts and display list of posts
For this First create a Class with name Post
class Post{ |
Now Create InheritedWidget
class _InheritedWidget extends InheritedWidget { final MyInheritedWidgetState data; @override |
in the above class we have defined MyInheritedWidgetState which will have the data,
so lets create that widget
class MyInheritedWidgetState extends State List _items = []; /// Getter (number of items) /// Helper method to add an Item |
This class contains list object(_items) wich stores created posts.
The method addItem() will be used to add the post into list while create post from child widgets
Now Design widgets to create Post and display list of Posts
Create Post Widget
class CreatePost extends StatelessWidget{ children: [ onSubmitted: (value){ hintText: "Enter Post Title", focusedBorder: OutlineInputBorder(
},
), _titleControler.text=""; ), } |
This create post widget having two textfileds to write Post title and Description and one button to create post.
Here we are using final MyInheritedWidgetState state = MyInheritedWidget.of(context) to add post into list.
Display List of Posts
class MyPosts extends StatefulWidget{
} itemBuilder: (context,index){ } |
Now here is time to use our InheritedWidget to load its child
class MyApp extends StatefulWidget{ } class _MyAppState extends State with TickerProviderStateMixin child: SafeArea(
} } |
Here we are taking the InheritedWidget as parent widget and passing SafeArea with TabBar as child
Now lets call this widget in the main method
void main() => runApp(MyApps()); class MyApps extends StatelessWidget { primarySwatch: Colors.blue, |
Now lets run the code and you will check the magic of changing the state object in two widgets
Article Contributed By :
|
|
|
|
1124 Views |