Skip to content

Instantly share code, notes, and snippets.

@raveesh-me
Created July 7, 2018 00:22
Show Gist options
  • Save raveesh-me/bf4f23eb76da8b4fb86630705815e42f to your computer and use it in GitHub Desktop.
Save raveesh-me/bf4f23eb76da8b4fb86630705815e42f to your computer and use it in GitHub Desktop.
An inherited callback pattern to change InheritedWidget state in flutter
import 'package:flutter/material.dart';
import 'package:flutter_login_manager/splash_screen.dart';
import 'package:flutter_login_manager/model/login_info.dart';
import 'package:flutter_login_manager/model/login.dart' as loginManager;
import 'package:flutter_login_manager/home_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
int number;
void numChangeCallback(int receivedNum) {
setState(() {
number = receivedNum;
});
}
@override
void initState() {
super.initState();
number = 0;
}
@override
Widget build(BuildContext context) =>
MaterialApp(
theme: ThemeData(
primarySwatch: Colors.red,
),
home: NumManager(
number: number,
callback: numChangeCallback,
child: Builder(builder: homeScreenBuilder)
),
);
}
Widget homeScreenBuilder(BuildContext context) {
int _number = NumManager
.of(context)
.number;
Function(int) _callback = NumManager
.of(context)
.callback;
return Scaffold(
appBar: AppBar(
title: Text('Inherited Callback Pattern'),
elevation: 0.0,
),
floatingActionButton: FloatingActionButton(onPressed: () {
_callback(++_number);
},child: Text('+1'),),
body: Center(
child: Text(_number.toString(),style: TextStyle(fontSize: 40.0, color: Colors.red, fontWeight: FontWeight.w900),),
),
);
}
class NumManager extends InheritedWidget {
final int number;
final Widget child;
final Function(int) callback;
final Key key;
NumManager({@required this.number,
@required this.callback,
@required this.child,
this.key})
: super(key: key);
@override
bool updateShouldNotify(NumManager oldWidget) {
return oldWidget.number == number;
}
static NumManager of(BuildContext context) =>
context.inheritFromWidgetOfExactType(NumManager);
}
@raveesh-me
Copy link
Author

InheritedCallbackPattern

Inherited Callback Allows you to change the values of the state distributed downwards by the InheritedWidget
inherited_callback

The Problem

The problem with InheritedWidgets is that all the fields inside it are final. As a result, we can only get, and not set the values inside it. This makes it ideal for holding state, but we do require some way to change state from below the tree.

The Solution

Inherit a callback. The Stateful Widget coupled with the InheritedWidget can expose a callback via the InheritedWidget.

The Result

It Works!

@rgr-dev
Copy link

rgr-dev commented Feb 21, 2019

This! is a simple Inheritedwidget Example! Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment