MOCKSTACKS
EN
Questions And Answers

More Tutorials









Flutter State & Inherited Widget Approach

Approach


This approach removes many of the requirements to use Stateful Widgets, often enabling the user to use Stateless Widgets instead.
You create a ‘state holder’ class that acts as a Widget in the Widget hierarchy. This class extends InheritedWidget, stores the state data and has a single child widget.
All the Widgets below this class can then be Stateless Widgets and they can use the BuildContext to access this InheritedWidget and its state data.

To see an example of this, see Chapter ‘State & InheritedWidget Approach’.

Exercise – ‘state_and_inherited_widget_add’

In this exercise, I put the state for the car list into CarsInheritedWidget and I access it in CarWidget. I add a toolbar button to add another car to the list.
Please read the summary before starting this exercise.

Step 1 – Create Default Flutter App

Follow the instructions in Generate Your First App Leave project open.

Step 2 – Replace Application Code

Replace contents of file ‘main.dart’ in folder ‘lib’ with the following:
import ‘package:collection/collection.dart’;
import ‘package:flutter/material.dart’;
void main() => runApp(new MyApp());
class Car {
String _make;
String _model;
String _imageSrc;
Car(this._make, this._model, this._imageSrc);
operator ==(other) =>
(other is Car) && (_make == other._make) && (_model == other._model);
int get hashCode => _make.hashCode ^ _model.hashCode ^ _imageSrc.hashCode;
}
class CarsInheritedWidget extends InheritedWidget {
List<Car> _cars = [
Car(
“Bmw”,
“M3",
“Https://media.ed.edmundsmedia.com/bmw/m3/2018/oem/2018_bmw_m3_sedan_base_fq_oem_4_150.jpg
Https://media.ed.edmundsmedia.com/bmw/m3/2018/oem/2018_bmw_m3_sedan_base_fq_oem_4_150.jpg
,
),
Car(
“Nissan”,
“GTR”,
“Https://media.ed.edmunds-media.com/nissan/gt-r/2018/oem/2018_nissan_gtr_coupe_nismo_fq_oem_1_150.jpg
Https://media.ed.edmunds-media.com/nissan/gt-r/2018/oem/2018_nissan_gtr_coupe_nismo_fq_oem_1_150.jpg
,
),
Car(
“Nissan”,
“Sentra”,
“Https://media.ed.edmundsmedia.com/nissan/sentra/2017/oem/2017_nissan_sentra_sedan_srturbo_fq_oem_4_150.jpg
Https://media.ed.edmundsmedia.com/nissan/sentra/2017/oem/2017_nissan_sentra_sedan_srturbo_fq_oem_4_150.jpg
,
)
];
CarsInheritedWidget(child) : super(child: child);
List<Car> get cars {
return _cars;
}
void addNissanSentra() {
_cars.add(Car(
“Nissan”,
“Sentra”,
“Https://media.ed.edmundsmedia.com/nissan/sentra/2017/oem/2017_nissan_sentra_sedan_srturbo_fq_oem_4_150.jpg
Https://media.ed.edmundsmedia.com/nissan/sentra/2017/oem/2017_nissan_sentra_sedan_srturbo_fq_oem_4_150.jpg
,
));
}
@override
bool updateShouldNotify(CarsInheritedWidget old) => true;
static CarsInheritedWidget of(BuildContext context) {
return (context.inheritFromWidgetOfExactType(CarsInheritedWidget));
}
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: ‘Flutter Demo’,
theme: new ThemeData(
// This is the theme of your application.
//
// Try running your application with “flutter run”. You’ll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// “hot reload” (press “r” in the console where you ran “flutter run”,
// or press Run > Flutter Hot Reload in IntelliJ). Notice that the
// counter didn’t reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: CarsInheritedWidget(MyHomePage(title: ‘Flutter Demo Home Page’)),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
List<CarWidget> carWidgets =
CarsInheritedWidget.of(context).cars.map((Car car) {
return CarWidget(car);
}).toList();
return new Scaffold(
appBar: new AppBar(
title: new Text(“Cars”),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () {
CarsInheritedWidget.of(context).addNissanSentra();
})
],
),
body: new ListView(children: carWidgets));
}
}
class CarWidget extends StatelessWidget {
CarWidget(this._car) : super();
final Car _car;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(20.0),
child: Container(
decoration: BoxDecoration(border: Border.all()),
padding: EdgeInsets.all(20.0),
child: Center(
child: Column(children: <Widget>[
Text(‘${_car._make} ${_car._model},
style: TextStyle(fontSize: 24.0)),
Padding(
padding: EdgeInsets.only(top: 20.0),
child: Image.network(_car._imageSrc))
]))));
}
}

Step 3 – Open Emulator & Run


Follow the instructions in Open Android Emulator & Run Your First App You should get something like the following as it is somewhat similar to the previous example:
However, note that the Add button on the toolbar does not work!!!!!

Conclusion

In this page (written and validated by ) you learned about Flutter State & Inherited Widget Approach . What's Next? If you are interested in completing Flutter tutorial, your next topic will be learning about: Flutter State and Scoped Model Approach.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.