Created with <3 with dartpad.dev.
Created
August 24, 2022 09:11
-
-
Save devxpy/41b7202409886f08b8ca8827b52dad10 to your computer and use it in GitHub Desktop.
crimson-glacier-2866
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MainApp()); | |
class MainApp extends StatefulWidget { | |
const MainApp({ | |
Key? key, | |
}) : super(key: key); | |
@override | |
State<MainApp> createState() => _MainAppState(); | |
} | |
class _MainAppState extends State<MainApp> { | |
int count = 1; | |
@override | |
Widget build(BuildContext context) { | |
return CounterInheritedWidget( | |
count: count, | |
child: MaterialApp( | |
home: DefaultTabController( | |
length: 2, | |
child: CounterTabs( | |
increment: increment, | |
), | |
), | |
), | |
); | |
} | |
void increment() { | |
setState(() { | |
count += 1; | |
}); | |
} | |
} | |
class CounterInheritedWidget extends InheritedWidget { | |
const CounterInheritedWidget({ | |
Key? key, | |
required this.count, | |
required Widget child, | |
}) : super(key: key, child: child); | |
final int count; | |
static CounterInheritedWidget of(BuildContext context) { | |
final CounterInheritedWidget? result = | |
context.dependOnInheritedWidgetOfExactType<CounterInheritedWidget>(); | |
assert(result != null, 'No CounterInheritedWidget found in context'); | |
return result!; | |
} | |
@override | |
bool updateShouldNotify(CounterInheritedWidget old) => count != old.count; | |
} | |
class CounterTabs extends StatelessWidget { | |
final VoidCallback increment; | |
const CounterTabs({Key? key, required this.increment}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
int count = CounterInheritedWidget.of(context).count; | |
return Scaffold( | |
floatingActionButton: FloatingActionButton( | |
child: Icon(Icons.add), | |
onPressed: () { | |
WidgetsBinding.instance.addPostFrameCallback((timeStamp) { | |
DefaultTabController.of(context)?.animateTo(0); | |
increment(); | |
}); | |
}, | |
), | |
appBar: AppBar( | |
title: Text("Actual value: $count"), | |
bottom: TabBar( | |
tabs: [ | |
Tab(text: "A"), | |
Tab(text: "B"), | |
], | |
), | |
), | |
body: TabBarView( | |
children: [ | |
Center(child: Text("Tab value: $count")), | |
Center(child: Text("Tab value: $count")), | |
], | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment