Flutter : Navigate with persistent side bar - flutter

I'm creating a flutter web project that looks like a dashboard. It has a side navigation and a body area that displays different screens.
To achieve this, I have divided my screen into two parts using Expanded and given them a flex value.
And to display different screens I have used IndexedStack.
Here is my main.dart file :
import 'package:flutter/material.dart';
import 'package:xxx/screens/courses/courses_screen.dart';
import 'package:xxx/side_navigation/menu_item.dart';
import 'package:xxx/componnents/header.dart';
import 'package:websafe_svg/websafe_svg.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
visualDensity: VisualDensity.adaptivePlatformDensity,
scaffoldBackgroundColor: Color(0xfffafafa),
fontFamily: 'Poppins',
),
home: MainScreenLayout(),
);
}
}
class MainScreenLayout extends StatefulWidget {
#override
_MainScreenLayoutState createState() => _MainScreenLayoutState();
}
class _MainScreenLayoutState extends State<MainScreenLayout> {
int selectedIndex = 0;
int hoverIndex = -1;
Color bgColor = Colors.transparent;
final List<MenuItem> menus = <MenuItem>[
MenuItem(label: 'Home', icon: Icons.home, screen: Container()),
MenuItem(label: 'Courses', icon: Icons.add, screen: Container()),
MenuItem(label: 'Students', icon: Icons.face_outlined, screen: Container()),
MenuItem(label: 'Home', icon: Icons.home, screen: Container()),
MenuItem(label: 'Courses', icon: Icons.add, screen: Container()),
MenuItem(label: 'Students', icon: Icons.face_outlined, screen: Container()),
];
final List<Widget> _screens = [
Container(
child: Image.asset(
'assets/try.png',
width: 100,
height: 100,
),
),
CoursesScreen(),
Container(
child: WebsafeSvg.asset('assets/folder_icon.svg'),
),
];
void _changeBg(int index) {
setState(() {
hoverIndex = index;
});
}
void _resetBg() {
setState(() {
hoverIndex = -1;
});
}
#override
Widget build(BuildContext context) {
double _width = MediaQuery.of(context).size.width;
return Scaffold(
body: Row(
children: [
Expanded(
flex: 2,
child: Container(
decoration: BoxDecoration(
color: Color(0xffffffff),
borderRadius: BorderRadius.only(
topRight: Radius.circular(_width * 0.03),
bottomRight: Radius.circular(_width * 0.03),
),
),
child: Column(
children: <Widget>[
SizedBox(
height: 50,
),
Flexible(
child: ListView.builder(
itemCount: menus.length,
itemBuilder: (BuildContext context, int index) {
return MouseRegion(
onHover: (event) {
_changeBg(index);
},
onExit: (event) {
_resetBg();
},
child: MenuItemLayout(
bgColor: hoverIndex == index
? Color(0xfffafafa)
: Colors.transparent,
menuItem: menus[index],
isSelected: selectedIndex == index ? true : false,
onTap: () {
setState(() {
selectedIndex = index;
});
},
),
);
},
),
),
],
),
),
),
Expanded(
flex: 7,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Header(
label: menus[selectedIndex].label,
),
Expanded(
child: Container(
child: IndexedStack(
index: selectedIndex,
children: _screens,
),
),
),
],
),
)
],
),
);
}
}
Here is the code for one of the screens (CourseScreen)
import 'package:flutter/material.dart';
import 'package:vjti_dashboard/componnents/responsive.dart';
import 'package:vjti_dashboard/screens/courses/courses_card.dart';
import 'package:vjti_dashboard/screens/courses/courses_model.dart';
class CoursesScreen extends StatelessWidget {
final List<CoursesModel> allCourses = [
CoursesModel(courseId: '123', courseName: 'Ecommerce'),
CoursesModel(courseId: '123', courseName: 'Big Data Analytics'),
CoursesModel(courseId: '123', courseName: 'User Experience Design'),
CoursesModel(courseId: '123', courseName: 'Technical Seminar'),
CoursesModel(courseId: '123', courseName: 'Elective 1'),
];
#override
Widget build(BuildContext context) {
return ListView(
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: [
Sample(
headingLabel: 'First Year',
allCourses: allCourses,
courseColor: Color(0xffEEF1E6),
),
Sample(
headingLabel: 'Second Year',
allCourses: allCourses,
courseColor: Color(0xffF9F1D6),
),
Sample(
headingLabel: 'Third Year',
allCourses: allCourses,
courseColor: Color(0xffE2F0CB),
),
],
);
}
}
class Sample extends StatelessWidget {
final String headingLabel;
final Color courseColor;
final List<CoursesModel> allCourses;
const Sample({Key key, this.allCourses, this.headingLabel, this.courseColor})
: super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
GestureDetector(
onTap: () {},
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Color(0xffd6d6d6),
width: 1.0,
),
),
),
child: Text(headingLabel),
),
),
GridView.count(
primary: false,
physics: ScrollPhysics(), // to disable GridView's scrolling
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 24, horizontal: 0),
crossAxisSpacing: 20,
childAspectRatio: 3 / 1,
mainAxisSpacing: 20,
crossAxisCount: Responsive.isDesktop(context)
? 4
: Responsive.isTablet(context)
? 3
: 2,
children: List.generate(
allCourses.length,
(index) {
return CourseCard(
coursesModel: allCourses[index],
containerColor: courseColor,
);
},
),
),
],
),
);
}
}
The side navigation works as it should and different pages are loaded while the navigation sticks to the left.
When I click on any widget on the CourseScreen, I want to open another screen that would replace CourseScreen but the navigation should still be there.
How can I achieve this?
Note : I'm new to flutter and most of the code that I have written is not perfect and probably is not a good way. I would appreciate if you can point out bad codes in the above files.
Thank You!!!

onGenerateRoute: (settings) => MaterialPageRoute(
builder: (context) => Parent(),

Related

How to do I add new column after endling of loop inside Gridview?

I want to add a new column after the end of the loop inside Gridview.
Right now in my code I add the append functionality in floatingActionButton but I want to add this append functionality in the column after every end of the column loop.
Like this:- need to add a new column after end of loop
Please see this image for a better understanding.
I hope you understand what I want to say.
Right now my output is like this:- see there is floatingActionButton where i add append functionality to add a new column
Here is my code:-
import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/custom/BorderIcon.dart';
import 'package:mindmatch/screens/Relation.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(new MaterialApp(
home: new Photos(),
));
}
class Photos extends StatefulWidget {
var usrid;
Photos({Key? key, #required this.usrid}) : super(key: key);
#override
_Photos createState() => _Photos();
}
class _Photos extends State<Photos>{
int counter = 0;
//List<Widget> _list = List<Widget>();
List<Widget> _list = <Widget> [];
#override
void initState() {
for (int i = 0; i < 2; i++) {
Widget child = _newItem(i);
_list.add(child);
};
}
void on_Clicked() {
Widget child = _newItem(counter);
setState(
() => _list.add(child),
);
}
Widget _newItem(int i) {
Key key = new Key('item_${i}');
Column child = Column(
key: key,
children: [
Stack(
children: [
Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Color(0xffa1a1a1),
),
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: SizedBox(
//width: 300,
height: 100,
child: Center(child:
Icon(
Icons.image,
color: Color(0xffcccccc),
size: 60,
),
),
),
),
Positioned(
top: 9,
right: 9,
child: InkWell(
onTap: () => _removeItem(i),
child: SvgPicture.asset(
width: 20,
'assets/images/close.svg',
height: 20,
),
),
)
]
),
]
);
counter++;
return child;
}
void _removeItem(int i) {
print("====remove $i");
print('===Removing $i');
setState(() => _list.removeAt(i));
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Photo'),
backgroundColor: Colors.deepPurpleAccent,
),
floatingActionButton: new FloatingActionButton(onPressed: on_Clicked, child: new
Icon(Icons.add),),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: Column(
children: [
Expanded(
child: GridView(
//padding: const EdgeInsets.all(8.0),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10.0,
mainAxisSpacing: 15,
//childAspectRatio: 2/1,
),
children: [
itemBuilder: List.generate(_list.length, (index) {
//generating tiles with people from list
return _newItem(index);
},
]
return Column(
)
),
)
)
],
),
),
);
}
}
Please help how I add a new Column after the end of the loop on that column i add onTap property where i add append functionality to add new column when click.
Here is the code of the new column with add icon
InkWell(
onTap: (){},
child: Column(
children: [
Stack(
children: const [
Card(
elevation: 0,
color: Color(0xff8f9df2),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Color(0xff8f9df2),
),
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: SizedBox(
//width: 300,
height: 100,
child: Center(child:
Icon(
Icons.add,
color: Colors.white,
size: 80.0,
),
),
),
)
]
),
]
),
)
You can extend item-count (item Length) by one and use last index to show add widget.
children: List.generate(itemLength + 1,
(index) => index == itemLength ? Text("new Item") : _newItem(index)),
I have created sample demo. you can foloow this. Hope this you want this same.
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class CustomObject{
String name;
bool isDummy;
CustomObject(this.name , this.isDummy);
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyClass(),
),
),
);
}
}
class MyClass extends StatefulWidget {
#override
State<MyClass> createState() => _MyClassState();
}
class _MyClassState extends State<MyClass> {
List<CustomObject> _list =[];
#override
void initState() {
_list =[
CustomObject('test',false),
CustomObject('test 2',false),
CustomObject('',true), ///this is extra item to achieve
];
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body : Padding(
padding: const EdgeInsets.all(8.00),
child : GridView.builder(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 3 / 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20),
itemCount: _list.length,
itemBuilder: (BuildContext ctx, index) {
return Container(
alignment: Alignment.center,
child: (!_list[index].isDummy) ? Text(_list[index].name) :
Icon(Icons.add,size: 40.00,),
decoration: BoxDecoration(
color: Colors.amber,
borderRadius: BorderRadius.circular(15)),
);
}),
),
);
}
}
Output :
Let me know if any query or anything.

flutter transfer data (color) to create a new widget

I'm creating a calendar app. The problem that I'm now facing is that I want to create a new user of the calendar. The user has the properties (which are now important) image, name and color.
I created a new File For the property color, in which the color can be changed. But I don't know how I can transfer the new color in the other file, so that I can use it to create the user.
I think it is possible to use the Material page route, but perhaps there is a more elegant way to handle this.
Does someone have an idea to handle this in a easy way?
UserSetScreen:
import 'package:calendar_vertical/screens/users_show_screen.dart';
import 'package:calendar_vertical/widgets/color_choose.dart';
import 'package:calendar_vertical/widgets/image_input.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class UserSetScreen extends StatefulWidget {
static const routeName = '/userSetScreen';
#override
State<UserSetScreen> createState() => _UserSetScreenState();
}
class _UserSetScreenState extends State<UserSetScreen> {
final _titleController = TextEditingController();
static const values = <String>[
'Administrator',
'normaler Nutzer',
'eingeschränkter Nutzer'
];
String selectedValue = values.first;
void _saveValues(User user) {
final neuerNutzer = User(
id: DateTime.now().toString(),
name: _titleController.text,
color: Colors.amber,
setAppointments: false,
administrator: false,
);
}
#override
Widget build(BuildContext context) {
final colorData = Provider.of<ColorChoose>(context);
return Scaffold(
appBar: AppBar(
title: Text('Person hinzufügen'),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).pushNamed(UsersShowScreen.routeName);
},
icon: Icon(Icons.people),
),
],
),
body: Column(
children: [
Center(
child: ImageInput(),
),
Expanded(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(10),
child: Column(
children: [
TextField(
decoration: InputDecoration(labelText: 'Name'),
controller: _titleController,
),
ColorChoose(),
//CheckboxListTile(
// value: value,
// onChanged: (value) => setState(() => this.value = value!),
// title: Text('Administrator'),
// controlAffinity: ListTileControlAffinity.leading,
//)
],
),
),
))
],
),
);
}
ColorChoose:
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
class ColorChoose extends StatefulWidget {
#override
State<ColorChoose> createState() => _ColorChooseState();
}
class _ColorChooseState extends State<ColorChoose> {
Color currentColor = Colors.white;
#override
Widget build(BuildContext context) {
return Row(
children: [
Text('Farbe: '),
Container(
decoration: BoxDecoration(
color: currentColor,
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 10.0),
margin: EdgeInsets.only(left: 10.0),
),
Spacer(),
ElevatedButton(
onPressed: () => _showColorPicker(context),
child: Text(
'Farbe ändern',
),
),
],
);
}
void _showColorPicker(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Farbe wählen'),
titlePadding: const EdgeInsets.all(0.0),
contentPadding: const EdgeInsets.all(0.0),
content: SingleChildScrollView(
child: Wrap(
children: [
Container(
width: 300,
height: 300,
child: BlockPicker(
pickerColor: currentColor,
onColorChanged: (color) => setState(
() => this.currentColor = color,
),
),
)
],
),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Close'),
)
],
),
);
}
}
Thank you very much.
Best regards
Patrick
I guess the best variant is to use GetX or another state manager.
Another way - to choose color right from the user screen, showing a dialog.
Finally you can pass valuenotifier to your color ColorChoose widget.

Flutter - Find cards by names

I am new to flutter and I have a program that shows several cards and I have a question about how to make a card finder, I am using this code:
_card(
String phrase,
) {
return SliverToBoxAdapter(
child: Card(
margin: EdgeInsets.only(right: 50, left: 50, top: 20),
child: InkWell(
onTap: () {},
child: Column(children: <Widget>[
SizedBox(height: 15.0),
Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Text(
phrase,
style: TextStyle(
fontFamily: 'Circular',
fontSize: 17.0,
color: Colors.grey[800]),
),
),
SizedBox(height: 15.0),
]),
),
),
);
}
and I use this to make the various cards:
return Scaffold(
body: Stack(children: [
CustomScrollView(physics: BouncingScrollPhysics(), slivers: <Widget>[
_card('Abrir'),
_card('Alzar'),
_card('Aprender'),
_card('Caer'),
_card('Cerrar'),
_card('Cocinar'),
_card('Correr'),
_card('Cortar'),
_card('Enseñar'),
_card('Estar'),
_card('Hay'),
_card('Levantarse'),
_card('Mirar'),
_card('Oler'),
_card('Saltar'),
_card('Sentar'),
_card('Ser'),
_card('Tocar'),
_card('Tomar'),
_card('Tropezar'),
]),
]),
);
I really appreciate any help, thanks
Here is a solution using:
hooks_riverpod for State Management
fuzzy for fuzzy search
Full source code for easy copy-paste
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fuzzy/fuzzy.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
runApp(
ProviderScope(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
),
);
}
class HomePage extends HookWidget {
#override
Widget build(BuildContext context) {
final phrases = useProvider(filteredPhrasesProvider);
return Scaffold(
body: ListView(
physics: BouncingScrollPhysics(),
children: [
TextField(
autofocus: true,
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Search',
),
onChanged: (value) =>
context.read(searchTermsProvider).state = value,
),
...phrases.map((phrase) => _Card(phrase: phrase)).toList(),
],
),
);
}
}
class _Card extends StatelessWidget {
final String phrase;
const _Card({
Key key,
this.phrase,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.all(10.0),
child: InkWell(
onTap: () {},
child: Padding(
padding: EdgeInsets.all(15.0),
child: Text(
phrase,
style: TextStyle(
fontFamily: 'Circular',
fontSize: 17.0,
color: Colors.grey[800],
),
),
),
),
);
}
}
final searchTermsProvider = StateProvider<String>((ref) => '');
final phrasesProvider = Provider<List<String>>(
(ref) => [
'Abrir',
'Alzar',
'Aprender',
'Caer',
'Cerrar',
'Cocinar',
'Correr',
'Cortar',
'Enseñar',
'Estar',
'Hay',
'Levantarse',
'Mirar',
'Oler',
'Saltar',
'Sentar',
'Ser',
'Tocar',
'Tomar',
'Tropezar',
],
);
final filteredPhrasesProvider = Provider<List<String>>((ref) {
final phrases = ref.watch(phrasesProvider);
final searchTerms = ref.watch(searchTermsProvider).state;
return searchTerms.isEmpty
? phrases
: Fuzzy<String>(phrases, options: FuzzyOptions(threshold: .4))
.search(searchTerms)
.map((result) => result.item)
.toList();
});
First you must change the logic of your code, create a List and then create the cards, so that the search engine works with the list
Create list:
final List<String> actions = ["Abrir", "Alzar", "Enseñar", "Sentar", "Mirar"];
Next, use List.generate or List.builder to create cards in the slivers
return Scaffold(
body: Stack(children: [
CustomScrollView(
physics: BouncingScrollPhysics(),
slivers: List.generate(actions.length, (i) => _cards(actions[i])
),
]),
);
Finally in your seacher, use this logic, the "contains" is optional, you can change the logic in the if
void search(String data) {
for(int i = 0; i < actions.length; i++) {
if(actions[i].contains(data)) {
print(actions[i]);
// In your case show card or add in another list to show after
}
}
}

Why isn't Navigator.pop() refreshing data?

Hi guys I'm trying to build an app with flutter, so I have two screens HomeScreen() and RoutineScreen(). The first one is a Scaffold and in the body has a child Widget (a ListView called RoutinesWidget()) with all the routines. And the second one is to create a routine. The thing is, that when I create the routine, I use a button to pop to the HomeScreen() but it doesn't refresh the ListView (I'm guessing that it's because when I use Navigator.pop() it refreshes the Scaffold but not the child Widget maybe?)
HomeScreen() code here:
import 'package:flutter/material.dart';
import 'package:workout_time/constants.dart';
import 'package:workout_time/Widgets/routines_widget.dart';
import 'package:workout_time/Widgets/statistics_widget.dart';
import 'package:workout_time/Screens/settings_screen.dart';
import 'package:workout_time/Screens/routine_screen.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int _selectedIndex = 0;
List<Widget> _views = [
RoutinesWidget(),
StatisticsWidget(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: kThirdColor,
appBar: AppBar(
leading: Icon(Icons.adb),
title: Text("Workout Time"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.settings),
onPressed: () => Navigator.push(context,
MaterialPageRoute(builder: (context) => SettingsScreen()))),
],
),
body: _views[_selectedIndex],
floatingActionButton: (_selectedIndex == 1)
? null
: FloatingActionButton(
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RoutineScreen(null)));
setState(() {});
},
child: Icon(
Icons.add,
color: kSecondColor,
size: 30.0,
),
elevation: 15.0,
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
bottomItems(Icon(Icons.fitness_center_rounded), "Routines"),
bottomItems(Icon(Icons.leaderboard_rounded), "Statistics"),
],
currentIndex: _selectedIndex,
onTap: (int index) => setState(() => _selectedIndex = index),
),
);
}
}
BottomNavigationBarItem bottomItems(Icon icon, String label) {
return BottomNavigationBarItem(
icon: icon,
label: label,
);
}
RoutinesWidget() code here:
import 'package:flutter/material.dart';
import 'package:workout_time/Services/db_crud_service.dart';
import 'package:workout_time/Screens/routine_screen.dart';
import 'package:workout_time/constants.dart';
import 'package:workout_time/Models/routine_model.dart';
class RoutinesWidget extends StatefulWidget {
#override
_RoutinesWidgetState createState() => _RoutinesWidgetState();
}
class _RoutinesWidgetState extends State<RoutinesWidget> {
DBCRUDService helper;
#override
void initState() {
super.initState();
helper = DBCRUDService();
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: helper.getRoutines(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
Routine routine = Routine.fromMap(snapshot.data[index]);
return Card(
margin: EdgeInsets.all(1.0),
child: ListTile(
leading: CircleAvatar(
child: Text(
routine.name[0],
style: TextStyle(
color: kThirdOppositeColor,
fontWeight: FontWeight.bold),
),
backgroundColor: kAccentColor,
),
title: Text(routine.name),
subtitle: Text(routine.exercises.join(",")),
trailing: IconButton(
icon: Icon(Icons.delete_rounded),
color: Colors.redAccent,
onPressed: () {
setState(() {
helper.deleteRoutine(routine.id);
});
},
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RoutineScreen(routine))),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
color: kSecondColor,
);
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}
}
RoutineScreen() code here:
import 'package:flutter/material.dart';
import 'package:workout_time/Models/routine_model.dart';
import 'package:workout_time/Widgets/type_card_widget.dart';
import 'package:workout_time/constants.dart';
import 'package:workout_time/Services/db_crud_service.dart';
class RoutineScreen extends StatefulWidget {
final Routine _routine;
RoutineScreen(this._routine);
#override
_RoutineScreenState createState() => _RoutineScreenState();
}
class _RoutineScreenState extends State<RoutineScreen> {
DBCRUDService helper;
final _nameController = TextEditingController();
final _descriptionController = TextEditingController();
bool _type = true;
int _cycles = 1;
int _restBetweenExercises = 15;
int _restBetweenCycles = 60;
#override
void initState() {
super.initState();
helper = DBCRUDService();
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.pop(context),
),
title: widget._routine != null
? Text(widget._routine.name)
: Text("Create your routine"),
actions: [
IconButton(
icon: Icon(Icons.done_rounded),
onPressed: createRoutine,
)
],
bottom: TabBar(
tabs: [
Tab(
text: "Configuration",
),
Tab(
text: "Exercises",
),
],
),
),
body: TabBarView(children: [
//_routine == null ? ConfigurationNewRoutine() : Text("WIDGET N° 1"),
ListView(
children: [
Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: [
Text(
"Name:",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(
width: 40.0,
),
Expanded(
child: TextField(
textAlign: TextAlign.center,
controller: _nameController,
),
),
],
),
),
SizedBox(
height: 20.0,
),
Card(
margin: EdgeInsets.all(15.0),
color: kSecondColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Container(
padding: EdgeInsets.all(15.0),
child: Column(
children: [
Text(
"Type",
style: TextStyle(fontSize: 25.0),
),
Row(
children: [
Expanded(
child: TypeCard(
Icons.double_arrow_rounded,
_type == true ? kFirstColor : kThirdColor,
() => setState(() => _type = true),
"Straight set",
),
),
Expanded(
child: TypeCard(
Icons.replay_rounded,
_type == false ? kFirstColor : kThirdColor,
() => setState(() => _type = false),
"Cycle",
),
),
],
),
],
),
),
),
SizedBox(
height: 20.0,
),
Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: [
Text(
"N° cycles:",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(
width: 40.0,
),
Expanded(
child: Text("Hello"),
),
],
),
),
SizedBox(
height: 20.0,
),
],
),
Text("WIDGET N° 2"),
]),
),
);
}
void createRoutine() {
List<String> _exercises = ["1", "2"];
List<String> _types = ["t", "r"];
List<String> _quantities = ["30", "20"];
Routine routine = Routine({
'name': _nameController.text,
'description': "_description",
'type': _type.toString(),
'cycles': 1,
'numberExercises': 2,
'restBetweenExercises': 15,
'restBetweenCycles': 60,
'exercises': _exercises,
'types': _types,
'quantities': _quantities,
});
setState(() {
helper.createRoutine(routine);
Navigator.pop(context);
});
}
}
Any idea what can I do to make it work? Thank you
Make it simple
use Navigator.pop() twice
so that the current class and old class in also removed
from the stack
and then use Navigator.push()
When you push a new Route, the old one still stays in the stack. The new route just overlaps the old one and forms like a layer above the old one. Then when you pop the new route, it will just remove the layer(new route) and the old route will be displayed as it was before.
Now you must be aware the Navigator.push() is an asynchronous method and returns a Future. How it works is basically when you perform a Navigator.push(), it will push the new route and will wait for it to be popped out. Then when the new route is popped, it returns a value to the old one and that when the future callback will be executed.
Hence the solution you are looking for is add a future callback like this after your Navigator.push() :
Navigator.push(context,
MaterialPageRoute(builder: (context) => SettingsScreen())
).then((value){setState(() {});}); /// A callback which is executed after the new route will be popped. In that callback, you simply call a setState and refresh the page.

Flutter TabBarView and BottomNavigationBar pages are not refreshing with SetState

I have the following Flutter BottomNavigationBar, I have 3 children page widgets. As soon as the user writes a review and press the submit button, I am calling the void _clear() which resets the values in the textfield widgets. This method is inside and called from the WriteReview widget but is not working, the screen is not refreshing. The data it self is being reset but the UI has not be refreshed. I tried with and without setState(){ _clear()}; but no results.
I have similar issue with the TabBarView. What I would expect as a result would be the selected widget page to be refreshed.
I assume is something different on how the widgets are being handled in the TabBarView and BottomNavigationBar that I am missing.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class HomeView extends StatefulWidget {
#override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
final String _writeReviewLabel = 'Write review';
final String _searchLabel = 'Search';
final String _accountLabel = 'Account';
var _currentIndex = 0;
final List<Widget> _bottomBarItems = [
WriteReviewView(),
SearchView(),
UserAccountView()
];
#override
Widget build(BuildContext context) {
final accentColor = Theme.of(context).accentColor;
final primaryColor = Theme.of(context).primaryColor;
return BaseView<HomePresenter>(
createPresenter: () => HomePresenter(),
onInitialize: (presenter) {
_currentIndex = ModalRoute.of(context).settings.arguments;
},
builder: (context, child, presenter) => Scaffold(
bottomNavigationBar: BottomNavigationBar(
backgroundColor: primaryColor,
selectedItemColor: accentColor,
unselectedItemColor: Colors.white,
elevation: 0,
currentIndex: _currentIndex,
onTap: (index) {
onTabTapped(index, presenter);
},
items: [
BottomNavigationBarItem(
activeIcon: Icon(Icons.rate_review),
icon: Icon(Icons.rate_review),
title: Text(_writeReviewLabel),
),
BottomNavigationBarItem(
activeIcon: Icon(Icons.search),
icon: Icon(Icons.search),
title: Text(_searchLabel),
),
BottomNavigationBarItem(
activeIcon: Icon(Icons.person),
icon: Icon(Icons.person),
title: Text(_accountLabel)),
],
),
body: _bottomBarItems[_currentIndex]),
);
}
void onTabTapped(int index, HomePresenter presenter) {
if (index == _currentIndex) {
return;
}
if (presenter.isAuthenticated) {
setState(() {
_currentIndex = index;
});
} else {
presenter.pushNamed(context, Routes.login, arguments: () {
if (presenter.isAuthenticated) {
Future.delayed(const Duration(microseconds: 500), () {
setState(() {
_currentIndex = index;
});
});
}
});
}
}
}
Write Review View
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'base/BaseView.dart';
class WriteReviewView extends StatefulWidget {
#override
_WriteReviewViewState createState() => _WriteReviewViewState();
}
class _WriteReviewViewState extends State<WriteReviewView> {
final String _locationLabel = 'Location';
final String _reviewLabel = 'Review';
#override
Widget build(BuildContext context) {
return BaseView<WriteReviewPresenter>(
createPresenter: () => WriteReviewPresenter(),
onInitialize: (presenter) {
presenter.init();
},
builder: (context, child, presenter) => Container(
color: Theme.of(context).backgroundColor,
child: _body(presenter),
));
}
Widget _body(WriteReviewPresenter presenter) {
final height = MediaQuery.of(context).size.height;
return LayoutBuilder(builder: (context, constraint) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraint.maxHeight),
child: IntrinsicHeight(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
margin: EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 8.0),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 10, bottom: 20),
child: Row(
children: [
Icon(Icons.location_on,
color: Theme.of(context).cursorColor),
SectionTitle(_locationLabel),
],
),
),
ChooseAddressButton(presenter.addressContainer.address, () {
presenter.navigateNewAddress(context);
}),
SizedBoxes.medium,
],
),
),
),
Card(
margin: EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 8.0),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
children: [
Padding(
padding: EdgeInsets.only(top: 10),
child: Row(
children: [
Icon(Icons.star, color: Theme.of(context).indicatorColor),
SectionTitle(_reviewLabel),
],
),
),
SizedBoxes.medium,
CustomTextFormField(
data: presenter.reviewContainer.review,
showMinimum: true,
characterLimit: 50,
maxLines: 4,
height: 100),
ModifyRatingBar(50.0, presenter.reviewContainer.rating, false),
Padding(
padding: EdgeInsets.symmetric(vertical: 5),
child: Divider(indent: 40, endIndent: 40)),
],
),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Card(
color: Theme.of(context).accentColor,
child: FlatButton(
onPressed: () {
_submit(context, presenter);
},
child: Text('Submit',style:TextStyle(fontWeight: FontWeight.bold,fontSize: 18,color: Colors.white)),
),
),
),
],
),
),
),
);
});
}
void _submit(BuildContext context, WriteReviewPresenter presenter) async {
LoadingPopup.show(context);
final status = await presenter.submit(context);
LoadingPopup.hide(context);
if (status == ReviewStatus.successful) {
PostCompletePopup.show(context);
setState(() {
presenter.clear();
});
} else {
presenter.showError(context, status);
}
}
}
setState() only refreshes the widget that called it, and all the widgets under it.
When calling setState()from WriteReview widget, it will not update the HomeView widget. Try moving the setState()call to the HomeView widget using some sort of callback.