I have the following class for holding my state:
import 'package:flutter/foundation.dart';
enum ActiveProduct {
HOME,
BURGUNDY,
VIRTUAL
}
class ActiveProductModel extends ChangeNotifier {
ActiveProduct _activeProduct = ActiveProduct.HOME;
ActiveProduct get value => _activeProduct;
void set(ActiveProduct newValue) {
_activeProduct = newValue;
notifyListeners();
}
}
Whenever the "ActiveProduct" changes, I want to change the selected tab in a TabView.
Currently I have setup the application like this:
class MainScaffold extends StatelessWidget {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
body: TabBarView(
children: [
Text("hello! abc"),
Text("hello! sdsadsa"),
Text("hello! 231321"),
],
),
),
);
}
}
How can I change the selected tab in the TabBarView when the ActiveProduct changes?
I have tried wrapping the MainScaffold in a Consumer and set the initialIndex value of DefaultTabController. This didn't work however.
I am using the Provider package for state management.
What I would do is transforming your MainScaffold into a StatelessWidget and then, I would not use a DefaultTabController but instead I would use a TabController and pass it as an argument to the TabBarView.
Then in the initState of the MainScaffoldState, I would listen on the ActiveProductModel and use tabController.animateTo(yourpage) whenever something is fired.
I'm not sure that I was very clear in my explanation so here is an example:
class MainScaffold extends StatefulWidget {
#override
_MainScaffoldState createState() => _MainScaffoldState();
}
class _MainScaffoldState extends State<MainScaffold> with SingleTickerProviderStateMixin {
TabController tabController;
/// Just for the example
ActiveProductModel activeProductModel = ActiveProductModel();
#override
void initState() {
// Initiate the tabController
tabController = TabController(vsync: this, length: 3);
activeProductModel.addListener(() {
if (mounted)
/// Here you can do whatever you want, just going to page 2 for the example.
tabController.animateTo(2);
});
super.initState();
}
#override
void dispose() {
tabController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: TabBarView(
controller: tabController,
children: <Widget>[
Text("hello! abc"),
Text("hello! sdsadsa"),
Text("hello! 231321"),
],
),
);
}
}
Related
I would like to call a fonction when my ExpandablePanel is expanded, with ExpansionTile I do this with onExpansionChanged but here I don't want to use ExpansionTile,
Doesn't anyone have a solution ?
Thanks.
Use an ExpandableControllerand an ExpandableNotifier:
class MyWidget extends StatefulWidget {
const MyWidget({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() => _MyWidget();
}
class _MyWidget extends State<MyWidget> {
final ExpandableController expandableController = ExpandableController();
void onExpandableControllerStateChanged() {
if (expandableController.expanded) {
// Do your stuff when panel got expanded here
} else {
// Do your stuff when panel got collapsed here
}
}
#override
void initState() {
super.initState();
expandableController.addListener(onExpandableControllerStateChanged);
}
#override
void dispose() {
expandableController.removeListener(onExpandableControllerStateChanged);
super.dispose();
}
#override
Widget build(BuildContext context) {
return ExpandableNotifier(
controller: expandableController,
child: ExpandablePanel(
header: HeaderWidget(),
collapsed: CollapsedWidget(),
expanded: ExpandedWidget(),
),
);
}
}
You can put the ExpansionPanel inside an ExpansionPanelList and inside it will have a property called expansionCallback
You can wrap ExpansionPanel with ExpansionPanelList, so that you can access to a callback function named expansionCallback. Take a look at the snippet below:
ExpansionPanelList(
animationDuration: const Duration(milliseconds:1000),
children: [
ExpansionPanel(), //..your expansionPanel here
],
expansionCallback: (int item, bool status) {
//status is what you're looking for
},
),
I'm trying to create a custom menu bar in my app. Right now, the biggest issue I'm having is passing a state for when it's expanded to it's children after a setState occurs.
I thought about inheritance, but from what I've tried all inheritance needs to be in-line. I can't create a widget where the children [] are fed into the constructor on an ad-hoc basis.
My current approach is to use a GlobalKey to update the State of the children widgets being inserted into the StateFul while updating them directly.
The children for my MenuBar are declared as:
List<MenuBarItem> menuItems;
MenuBarItem is an abstract interface class that I intend to use to limit the widgets that can be fed in as menuItems to my MenuBar.
abstract class iMenuItem extends Widget{}
class MenuBarItem extends StatefulWidget implements iMenuItem{
At some iterations of this script, I had a bool isExpanded as part of the iMenuItem, but determined it not necessary.
Here is my code at its current iteration:
My Main:
void main() {
// runApp(MainApp());
//runApp(InherApp());
runApp(MenuBarApp());
}
class MenuBarApp extends StatelessWidget{
#override
Widget build(BuildContext context){
return MaterialApp(
home: Scaffold(
body: MenuBar(
menuItems: [
// This one does NOT work and is where I'm trying to get the
// value to update after a setState
MenuBarItem(
myText: 'Outsider',
),
],
),
),
);
}
}
My Code:
import 'package:flutter/material.dart';
/// Primary widget to be used in the main()
class MenuBar extends StatefulWidget{
List<MenuBarItem> menuItems;
MenuBar({
required this.menuItems,
});
#override
State<MenuBar> createState() => MenuBarState();
}
class MenuBarState extends State<MenuBar>{
bool isExpanded = false;
late GlobalKey<MenuBarContainerState> menuBarContainerStateKey;
#override
void initState() {
super.initState();
menuBarContainerStateKey = GlobalKey();
}
#override
Widget build(BuildContext context){
return MenuBarContainer(
menuItems: widget.menuItems,
);
}
}
class MenuBarContainer extends StatefulWidget{
List<MenuBarItem> menuItems;
late Key key;
MenuBarContainer({
required this.menuItems,
key,
}):super(key: key);
#override
MenuBarContainerState createState() => MenuBarContainerState();
}
class MenuBarContainerState extends State<MenuBarContainer>{
bool isExpanded = false;
#override
void initState() {
super.initState();
isExpanded = false;
}
#override
Widget build(BuildContext context){
List<Widget> myChildren = [
ElevatedButton(
onPressed: (){
setState((){
this.isExpanded = !this.isExpanded;
});
},
child: Text('Push Me'),
),
// This one works. No surprise since it's in-line
MenuBarItem(isExpanded: this.isExpanded, myText: 'Built In'),
];
myChildren.addAll(widget.menuItems);
return Container(
child: Column(
children: myChildren,
),
);
}
}
/// The item that will appear as a child of MenuBar
/// Uses the iMenuItem to limit the children to those sharing
/// the iMenuItem abstract/interface
class MenuBarItem extends StatefulWidget implements iMenuItem{
bool isExpanded;
String myText;
MenuBarItem({
key,
this.isExpanded = false,
required this.myText,
}):super(key: key);
#override
State<MenuBarItem> createState() => MenuBarItemState();
}
class MenuBarItemState extends State<MenuBarItem>{
#override
Widget build(BuildContext context){
GlobalKey<MenuBarState> _menuBarState;
return Row(
children: <Widget> [
Text('Current Status:\t${widget.isExpanded}'),
Text('MenuBarState GlobalKey:\t${GlobalKey<MenuBarState>().currentState?.isExpanded ?? false}'),
Text(widget.myText),
],
);
}
}
/// To give a shared class to any children that might be used by MenuBar
abstract class iMenuItem extends Widget{
}
I've spent 3 days on this, so any help would be appreciated.
Thanks!!
I suggest using ChangeNotifier, ChangeNotifierProvider, Consumer and context.read to manage state. You have to add this package and this import: import 'package:provider/provider.dart';. The steps:
Set up a ChangeNotifier holding isExpanded value, with a setter that notifies listeners:
class MyNotifier with ChangeNotifier {
bool _isExpanded = false;
bool get isExpanded => _isExpanded;
set isExpanded(bool isExpanded) {
_isExpanded = isExpanded;
notifyListeners();
}
}
Insert the above as a ChangeNotifierProvider in your widget tree at MenuBar:
class MenuBarState extends State<MenuBar> {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => MyNotifier(),
child: MenuBarContainer(
menuItems: widget.menuItems,
));
}
}
After this you can easily read and write the isExpanded value from anywhere in your widget tree under the ChangeNotifierProvider, for example:
ElevatedButton(
onPressed: () {
setState(() {
final myNotifier = context.read<MyNotifier>();
myNotifier.isExpanded = !myNotifier.isExpanded;
});
},
child: Text('Push Me'),
),
And if you want to use this state to automatically build something when isExpanded is changed, use Consumer, which will be notified automatically upon every change, for example:
class MenuBarItemState extends State<MenuBarItem> {
#override
Widget build(BuildContext context) {
return Consumer<MyNotifier>(builder: (context, myNotifier, child) {
return Row(
children: <Widget>[
Text('Current Status:\t${myNotifier.isExpanded}'),
Text(widget.myText),
],
);
});
}
}
I have a PageView with four pages in it. I want to start on the third page. That means there are two pages available when the user scrolls up and one page when the user scrolls down.
I tried:
home: PageView(
controller: MyPageController(),
children: [Page1(), Page2(), Page3(), Page4()],
scrollDirection: Axis.vertical,
),
With:
class MyPageController extends PageController {
#override
int get initialPage => 3;
}
Unfortunately, that doesn't help me.
PageController constructor has named parameter initialPage. You can use it, just create the controller somewhere outside of build function:
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
PageController controller;
#override
void initState() {
super.initState();
controller = PageController(initialPage: 3);
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: PageView(
controller: controller,
children: [
for (var i = 0; i < 4; i++)
Text('test $i')
],
scrollDirection: Axis.vertical,
)
)
),
);
}
}
For me initialization of PageController with initialPage didn't work for a large number of pages. I also noticed that there is scrolling animation which is undesirable if you want to land to desired page directly.
I used following
PageController _pageViewController = PageController();
#override
void initState() {
super.initState();
}
#override
void didChangeDependencies() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_pageViewController.hasClients)
_pageViewController.jumpToPage(3);
});
super.didChangeDependencies();
}
You need to set initial page like,
PageController _controller = PageController(initialPage: 3);
I'm new in Flutter and I am following this official example about text fields: https://flutter.dev/docs/cookbook/forms/text-field-changes
There is an axample for listen to changes in the controller of a text field widget. Please note this fragment of code _MyCustomFormState
final myController = TextEditingController();
#override
void initState() {
super.initState();
myController.addListener(_printLatestValue);
}
_printLatestValue() {
print("Second text field: ${myController.text}");
}
If I have two fields and two controllers, I would like to have just one listener, and display some message depending on which controller called the method. I would like to do something like this:
final myController1 = TextEditingController();
final myController2 = TextEditingController();
#override
void initState() {
super.initState();
myController1.addListener(_printLatestValue('message1'));
myController1.addListener(_printLatestValue('message2'));
}
_printLatestValue(message) {
print("Second text field: ${myController.text + message}");
}
which is not possible because the method addListener() uses some called VoidCallback, which have no arguments. At least that is what I understood from the Flutter docs.
So, if it is possible, how can I achieve what I'm looking for?
You're almost correct, but not quite. You're free to pass in any arguments to the listener. However, those arguments need to come from somewhere else - TextEditingController does not supply any, and it does not expect any return values. In other words, the signature should be something like: () => listener(...).
So to answer your question, you're free to do something like the following to distinguish the controllers:
void initState() {
super.initState();
firstController.addListener(() => _printLatestValue('first'));
secondController.addListener(() => _printLatestValue('second'));
}
Full working example:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Text controllers',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final firstController = TextEditingController();
final secondController = TextEditingController();
void initState() {
super.initState();
firstController.addListener(() => _printLatestValue('first'));
secondController.addListener(() => _printLatestValue('second'));
}
#override
void dispose() {
firstController.dispose();
secondController.dispose();
super.dispose();
}
_printLatestValue(message) {
if (message == 'first') {
print('Received form first controller: ${firstController.text}');
} else {
print('Received from second controller: ${secondController.text}');
}
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Controllers', style: TextStyle(fontSize: 18)),
),
body: Center(
child: Column(
children: <Widget>[
TextField(controller: firstController,),
TextField(controller: secondController,)
],
),
),
);
}
}
Note that in this case, listener will only print the text from a TextField that was changed.
I'm trying to change the active page index via a pagecontroller in Flutter, using the Bloc pattern and its throwing "'_positions.isNotEmpty': ScrollController not attached to any scroll views.".
This is my code:
WelcomeWizardScreen:
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertest/blocs/wizard/bloc/bloc.dart';
import 'package:fluttertest/screens/wizardsteps/joincongregation.dart';
import 'package:fluttertest/screens/wizardsteps/welcometomapman.dart';
class WelcomeWizardScreen extends StatefulWidget {
#override
_WelcomeWizardScreenState createState() => _WelcomeWizardScreenState();
}
class _WelcomeWizardScreenState extends State<WelcomeWizardScreen> {
final WizardBloc wizardBloc = WizardBloc();
#override
Widget build(BuildContext context) {
// TODO: implement build
return BlocProvider(
builder: (BuildContext context) => WizardBloc(),
child: PageView(
children: <Widget>[WelcomeToMapMan(), JoinCongregation()],
controller: wizardBloc.pageController,
),
);
}
}
WizardBloc:
import 'package:bloc/bloc.dart';
import 'package:flutter/widgets.dart';
import 'wizard_state.dart';
import 'wizard_event.dart';
class WizardBloc extends Bloc<WizardEvent, WizardState> {
int activeStep = 0;
final PageController pageController = PageController(initialPage: 0, keepPage: false, viewportFraction: 0.4);
#override
WizardState get initialState => WelcomeToMapManState();
#override
Stream<WizardState> mapEventToState(
WizardEvent event,
) async* {
if (event is ChangePage)
{
pageController.jumpToPage(event.pageIndex);
}
// TODO: Add Logic
}
Stream<WizardState> _mapJoinCongregationToState() async* {
}
}
One of the screens in the PageView:
class JoinCongregation extends StatelessWidget {
#override
Widget build(BuildContext context) {
final WizardBloc _wizardBloc = BlocProvider.of<WizardBloc>(context);
// TODO: implement build
return Column(
children: <Widget>[
Center(
child: Text("this is step 2"),
),
RaisedButton(
child: Text("back to step 1"),
onPressed: () => {_wizardBloc.dispatch(ChangePage(0))},
)
],
);
}
}
It seems like the PageViewController isn't "attached" to the PageView when it is called on to change pages, but it initalises correctly (on the correct page index).
How can I solve this? I'm fairly new to flutter.
You shouldn't create a PageController in a bloc because a bloc should not be coupled with the UI (theoretically you should be able to reuse your bloc between Flutter and AngularDart). Please refer to https://github.com/felangel/bloc/issues/18 for an example of how you can accomplish this.