Skip to content

Instantly share code, notes, and snippets.

@definev
Created December 18, 2021 12:56
Show Gist options
  • Save definev/d4fa6080925e7b095da2df6a255b72c8 to your computer and use it in GitHub Desktop.
Save definev/d4fa6080925e7b095da2df6a255b72c8 to your computer and use it in GitHub Desktop.
Nested WIdget experiment
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _text = "OPT_1";
bool isNested = false;
void changeMode() {
setState(() {
isNested = !isNested;
});
}
void changeText() {
setState(() {
if (_text == "OPT_1") {
_text = "OPT_2";
} else {
_text = "OPT_1";
}
});
}
Widget _nestedOption() {
return NestedWidget(
children: [
(child) {
print("Nested widget rebuilt!");
return Padding(
padding: const EdgeInsets.all(1),
child: child,
);
}
],
child: Text(_text),
);
}
Widget _normalOption() {
return CustomPaddingForLog(
child: Text(_text),
);
}
@override
Widget build(BuildContext context) {
print("Rebuilt in parent");
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: [
Expanded(
child: isNested ? _nestedOption() : _normalOption(),
),
Row(
children: [
ElevatedButton(
onPressed: changeText,
child: const Text("Rebuilt"),
),
ElevatedButton(
onPressed: changeMode,
child: const Text("Change mode"),
),
],
),
],
),
);
}
}
class CustomPaddingForLog extends StatelessWidget {
const CustomPaddingForLog({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
print("Rebuilt in normal");
return Padding(
padding: const EdgeInsets.all(1),
child: child,
);
}
}
typedef SingleChildWidgetConstructor = Widget Function(Widget child);
class NestedWidget extends StatelessWidget {
const NestedWidget({
Key? key,
required this.children,
required this.child,
}) : super(key: key);
final List<SingleChildWidgetConstructor> children;
final Widget child;
@override
Widget build(BuildContext context) {
Widget nestedChild = child;
for (final constructor in children.reversed) {
return constructor(nestedChild);
}
return nestedChild;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment