Persistent bottom navigation bar flutter - flutter

I used a bottom navigation bar in flutter using this widget,
how can I make that bottom navigation bar show on all the pages?
and can I make it appear when I choose a page from drawer??
please help me,

You can actually achieve this with the pageview widget
https://api.flutter.dev/flutter/widgets/PageView-class.html
With this, you can have all the pages inside one class and build the bottom navigation bar underneath the pageview widget. By default the pages are swipeable but you can disable it doing
Scaffold(
body:
Container(
child:
Column(
children: <Widget> [
PageView(
physics:new NeverScrollableScrollPhysics())
controller: _controller,
children: [
MyPage1(),
MyPage2(),
MyPage3(),
],
),
googleNavBar()
]
)
);

May I suggest you to use flutter builtin BottomNavigationBar widget instead of third party widget.
Here is my code you can modify as per you requirement. Hope this will help.
class DashboardScreen extends StatefulWidget {
#override
_DashboardScreenState createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> with SingleTickerProviderStateMixin {
final _selectedItemColor = Colors.white;
final _unselectedItemColor = Color(0xFF828282);
final _selectedBgColor = Color(0xFF00cde7);
final _unselectedBgColor = Colors.transparent;
int _currentIndex = 0;
GlobalKey<ScaffoldState> _key = GlobalKey();
// List of body of current screen you import/create from other dart file.
final List<Widget> _children = [
HomeScreen(),
AppointmentScreen(id: 1),
PaymentScreen(id: 1),
ProfileScreen(id: 1)
];
// List of dynamic app bar for different page. You can also import/create app bar easily
final List<Widget> _childAppBar = [
HomeAppBar(),
AppointmentAppBar(),
PaymentAppBar(),
ProfileAppBar()
];
void _onItemTapped(int index) {
setState(() {
_currentIndex = index;
});
debugPrint("Tapped item : $index");
}
Color _getBgColor(int index) =>
_currentIndex == index ? _selectedBgColor : _unselectedBgColor;
Color _getItemColor(int index) =>
_currentIndex == index ? _selectedItemColor : _unselectedItemColor;
Widget _buildIcon(IconData iconData, String text, int index) => Container(
width: MediaQuery.of(context).size.width,
height: kBottomNavigationBarHeight,
child: Material(
color: _getBgColor(index),
child: InkWell(
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
child: Column(
children: [
Icon(iconData, color: _getItemColor(index)),
Text(text,
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, fontFamily: 'Poppins', color: _getItemColor(index))),
],
),
),
],
),
onTap: () => _onItemTapped(index), // function responsible for navigation on tap
),
),
);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
key: _key,
appBar: _childAppBar.elementAt(_currentIndex), // this is dynamic app bar
body: _children.elementAt(_currentIndex), // this is dynamic body of the current screen
bottomNavigationBar:
BottomNavigationBar(
currentIndex: 0,
type: BottomNavigationBarType.fixed,
iconSize: 30.0,
items: [
BottomNavigationBarItem(
icon: _buildIcon(Icons.home, "Home", 0), // Check this _buildIcon function above
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.group, "Appointment", 1),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.add_circle_outline, "Make Payment", 2),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon( Icons.person_outline, "My Account", 3),
title: SizedBox.shrink(),
),
]
),
drawer: _currentIndex == 0 || _currentIndex == 3 ? Drawer( // check to show drawer on particular screen
child: ListView(
padding: const EdgeInsets.all(0.0),
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text("Mohammad Gayasuddin"),
accountEmail: Text("ladla8602#gmail.com"),
currentAccountPicture: CircleAvatar(
backgroundColor: Colors.white70,
)),
ListTile(
title: Text('Login'),
trailing: Icon(Icons.lock),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginScreen(),
),
);
}),
ListTile(
title: Text('Sign Up'),
trailing: Icon(Icons.add_circle_outline),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RegisterScreen(),
),
);
})
],
),
) : PreferredSize(
child: Container(),
preferredSize: Size(0.0, 0.0),
),
),
);
}
}

Related

How to add scroll into bottom navigation bar items

I have implemented an app that navigates through a few screens. I have added the bottom navigation bar and 1st tab I add a page with list view items with sqlflite data.I can't scroll list view data. other tabs I have added to show another screen.
code is below.
//this is my homepage screen
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
late List<LeaveModel> _leaveList = [];
final _userService = LeaveService();
int _selectedIndex = 0;
#override
void initState() {
getAllUserDetails();
super.initState();
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
I have create botom navigation bar with 4 item.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.menu),
onPressed: () {},
),
title: const Text('Leave Tracker'),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.notifications),
onPressed: () {},
),
IconButton(
icon: const Icon(Icons.add_box),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => AddLeave()))
.then((data) {
if (data != null) {}
getAllUserDetails();
});
},
)
],
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _selectedIndex,
onTap: _onItemTapped,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.man),
label: 'All',
),
BottomNavigationBarItem(
icon: Icon(Icons.sick_rounded),
label: 'Sick',
),
BottomNavigationBarItem(
icon: Icon(Icons.holiday_village),
label: 'Casual',
),
BottomNavigationBarItem(
icon: Icon(Icons.weekend),
label: 'Other',
),
],
),
From this 4 items goto different 3 screens.1st item link to same page.(HomePage())
body: Center(
child: _selectedIndex == 0
? myListView(context)
: _selectedIndex == 1
? AllSickLeave()
: _selectedIndex == 2
? AllCasualLeave()
: ViewOtherLeave(),
),
);
}
In HomePage() i have add listview and data taking from sqlflite database.
getAllUserDetails() async {
var users = await _userService.readAllLeave();
_leaveList = <LeaveModel>[];
users.forEach((leave) {
setState(() {
var leaveModel = LeaveModel();
leaveModel.id = leave['id'];
leaveModel.leaveType = leave['leaveType'];
leaveModel.leaveStartDate = leave['leaveStartDate'];
leaveModel.leaveEndDate = leave['leaveEndDate'];
leaveModel.reason = leave['reason'];
leaveModel.leaveDays = leave['leaveDays'];
_leaveList.add(leaveModel);
});
});
}
Widget myListView(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 5.0,
),
Text(
'All Leave Details',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
ListView.builder(
shrinkWrap: true,
itemCount: _leaveList.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(
'Leave Type : ${_leaveList[index].leaveType ?? ''}'),
subtitle: Text('Reason : ${_leaveList[index].reason}'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
onPressed: () {},
icon: Icon(
Icons.edit,
color: Colors.teal,
)),
IconButton(
onPressed: () {},
icon: Icon(
Icons.delete,
color: Colors.red,
)),
],
),
),
);
}),
],
),
),
);
}
}
You dont need to have multiple scaffold, and try this format
Widget myListView(BuildContext context) {
return ListView.builder(
padding: EdgeInsets.only(top: 25),
itemCount: _leaveList.length + 1,
itemBuilder: (context, index) {
if (index == 0)
return Text(
'All Leave Details',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
);
return Card(
child: ListTile(

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 how to save position of the reorderables package?

i tried the reorderables package https://pub.dev/packages/reorderables
I successed to move my dashboard blocs but when I restart app, my moves are removed.
So the solution can only be a sharedpref solution.
But I dont found how to save this information
I tried to save and load newIndex but without success
I tried to save and load List _tiles; but sharedpref can't save List
Here is my code example
List<Widget> _tiles;
void _onReorder(int oldIndex, int newIndex) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
Widget row = _tiles.removeAt(oldIndex);
_tiles.insert(newIndex, row);
//prefs.setListWidget('indexList', _tiles); not working
// prefs.setInt('index', newIndex ); not working
});
}
#override
void initState() {
super.initState();
_tiles = <Widget>[
//my widget1
//my widget2
//my widget3
//my widget4
//my widget5
//my widget6
//my widget7
//my widget8
//my widget9
]
}
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ReorderableWrap(
spacing: 0.0,
runSpacing:0,
maxMainAxisCount: 3,
minMainAxisCount: 3,
padding: const EdgeInsets.all(5),
children:_tiles,
onReorder: _onReorder,
onNoReorder: (int index) {
//this callback is optional
debugPrint('${DateTime.now().toString().substring(5, 22)} reorder cancelled. index:$index');
},
onReorderStarted: (int index) {
//this callback is optional
debugPrint('${DateTime.now().toString().substring(5, 22)} reorder started: index:$index');
}
)
]
);
}
}
edit : here is Widget 1. other widget are same
new Container (
width: SizeConfig.safeBlockHorizontal * 32,
height: 160,
child :
new Card(
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
color: Colors.white,
child:
Ink(
child: InkResponse(
splashFactory: InkRipple.splashFactory,
radius: 100,
onTap: () {
},
child:
Padding(
padding: const EdgeInsets.only(top:10),
child:
new Container(
padding: const EdgeInsets.all(0),
child :
new Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
height:25,
child :
new Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Icon(Icons.keyboard_arrow_right, color: Colors.white, size: 15.0),
Text('Planning',textAlign:TextAlign.center, style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: SizeConfig.safeBlockHorizontal * 4),
),
Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 15.0),
]
),
),
Padding(
padding: const EdgeInsets.all(5),),
Icon(Icons.event_available, color:Color(0xffff9a7b), size: 70.0),
],
),
))
),
)),
)
Here is my design
Edit #2
Now I tried to add my assets in the model, but I don't know how to do
void initState() {
// default models list
models = [
Model(index: 0, new Container (
width:90,
height: 90,
child :new FlareActor("assets/pierre.flr", alignment:Alignment.center, fit:BoxFit.contain, animation:"pierre")
), title: 'Coach'),
Model(index: 1, new Image.asset(
"assets/cup.png",
width: 50,
), title: 'Victories'),
Model(index: 2, icon: Icon(Icons.card_giftcard), title: 'Jeux'),
Model(index: 3, icon: Icon(Icons.wb_sunny), title: 'Sunny'),
Model(index: 4, icon: Icon(Icons.cloud), title: 'Cloud'),
Model(index: 5, icon: Icon(Icons.tv), title: 'TV'),
Model(index: 6, icon: Icon(Icons.place), title: 'Location'),
Model(index: 8, icon: Icon(Icons.music_note), title: 'Music'),
// More customization
Model(
index: 7,
icon: Icon(Icons.event_available, color: Color(0xffff9a7b)),
title: 'Planning'),
];
config();
super.initState();
}
This solution isn't a good one and I don't like it, but it works :D
I really appreciate it if anyone would refer a better one
Maybe for this project, it's good to use DB instead of SharedPreferences but here I used SharedPreferences.
The question is how to save the order of some widget(each time on reordering, the order of widget changes and we want to save the order of them, after restarting the app the saved order should be fetched).
SharedPreferences can also save a list of string, so what I did here was:
In the beginning, there should be a default list, that contains the initial order of widget's of the app.
Because widgets are somehow the same and only some of their info is different, I decided to define a model and work with models, instead of a whole complicated widget, I mean when I want to remove or change indexes I do it for a list of models rather than a list of widgets.
Here I supposed the model only contains a title, I also defined an index for it, so all I do is that when I reorder the widget, it reorders the list of models, to save the order, I save the index of models in any order they are now,
for example, if the initial order was [0, 1, 2, 3] let's say after reordering it's now [3, 0, 1, 2], I save this order, and for the next boot, I fetch the saved order([3, 0, 1, 2]) and then reorder the default list based on this fetched order.
Another solution would be to change the model's index and then show an ordered list of models based on their index.
Here is the code:
import 'package:flutter/material.dart';
import 'package:reorderables/reorderables.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: Page(),
),
),
),
);
class Page extends StatefulWidget {
const Page({Key key}) : super(key: key);
#override
_PageState createState() => _PageState();
}
class _PageState extends State<Page> {
SharedPreferences prefs;
List<Model> models;
#override
void initState() {
// default models list
models = [
Model(index: 0, title: 'Item 0'),
Model(index: 1, title: 'Item 1'),
Model(index: 2, title: 'Item 2'),
Model(index: 3, title: 'Item 3'),
];
config();
super.initState();
}
void config() async {
// Here we reset the default model based on saved order
await SharedPreferences.getInstance().then((pref) {
prefs = pref;
List<String> lst = pref.getStringList('indexList');
List<Model> list = [];
if (lst != null && lst.isNotEmpty) {
list = lst
.map(
(String indx) => models
.where((Model item) => int.parse(indx) == item.index)
.first,
)
.toList();
models = list;
}
setState(() {});
});
}
void _onReorder(int oldIndex, int newIndex) async {
Model row = models.removeAt(oldIndex);
models.insert(newIndex, row);
setState(() {
prefs.setStringList(
'indexList', models.map((m) => m.index.toString()).toList());
});
}
#override
Widget build(BuildContext context) {
return ReorderableWrap(
scrollDirection: Axis.vertical,
direction: Axis.vertical,
spacing: 0.0,
runSpacing: 0,
maxMainAxisCount: 3,
minMainAxisCount: 3,
padding: const EdgeInsets.all(5),
children: models
.map((m) => Card(
child: Container(
child: Text('${m.index} - ${m.title}'),
padding: EdgeInsets.all(24.0),
),
))
.toList(),
onReorder: _onReorder,
onNoReorder: (int index) {
//this callback is optional
debugPrint('${DateTime.now().toString().substring(5, 22)} ' +
'reorder cancelled. index:$index');
},
onReorderStarted: (int index) {
//this callback is optional
debugPrint('${DateTime.now().toString().substring(5, 22)} ' +
'reorder started: index:$index');
});
}
}
class Model {
int index;
String title;
Model({this.index, this.title});
#override
String toString() {
return '$index : $title';
}
}
Changes After Edit to the main question:
This version is based on the editing to the main question, I decided to keep the first answer unchanged because it's a more simple version and may help another viewer.
For the new model, as far as I could get, it has an icon, title, and an onTap functionality, I changed the model to have icon and title, but for the onTap, I wrote my own card version that gets a model and onTap functionality, I could add onTap to the model, but I thought it's better for future use or to use in other places, so I separated the onTap from the model, I also chose Icon for the model, it could be IconData (benefit of IconData is that you can choose customization for each icon and etc).
On my Card version (MyCard), I simply used a GestureDetector and Card to simulate the taps and card.
I wrote a FakePage that gets a model and if you Tap on each card it navigates to this page and shows some message based on the received model.
To clean the previously saved model in SharedPreferences, you should comment the part that fetches models order in config() and on the next refresh, you should uncomment it again.
Here is the new version of code:
import 'package:flutter/material.dart';
import 'package:reorderables/reorderables.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: Page(),
),
),
),
);
class Page extends StatefulWidget {
const Page({Key key}) : super(key: key);
#override
_PageState createState() => _PageState();
}
class _PageState extends State<Page> {
SharedPreferences prefs;
List<Model> models;
#override
void initState() {
// default models list
models = [
Model(index: 0, icon: Icon(Icons.people), title: 'Coach'),
Model(index: 1, icon: Icon(Icons.wb_incandescent), title: 'Victories'),
Model(index: 2, icon: Icon(Icons.card_giftcard), title: 'Jeux'),
Model(index: 3, icon: Icon(Icons.wb_sunny), title: 'Sunny'),
Model(index: 4, icon: Icon(Icons.cloud), title: 'Cloud'),
Model(index: 5, icon: Icon(Icons.tv), title: 'TV'),
Model(index: 6, icon: Icon(Icons.place), title: 'Location'),
Model(index: 8, icon: Icon(Icons.music_note), title: 'Music'),
// More customization
Model(
index: 7,
icon: Icon(Icons.event_available, color: Color(0xffff9a7b)),
title: 'Planning'),
];
config();
super.initState();
}
void config() async {
// Here we reset the default model based on saved order
await SharedPreferences.getInstance().then((pref) {
prefs = pref;
List<String> lst = pref.getStringList('indexList');
List<Model> list = [];
if (lst != null && lst.isNotEmpty) {
list = lst
.map(
(String indx) => models
.where((Model item) => int.parse(indx) == item.index)
.first,
)
.toList();
models = list;
}
setState(() {});
});
}
void _onReorder(int oldIndex, int newIndex) async {
Model row = models.removeAt(oldIndex);
models.insert(newIndex, row);
setState(() {
prefs.setStringList(
'indexList', models.map((m) => m.index.toString()).toList());
});
}
#override
Widget build(BuildContext context) {
return ReorderableWrap(
spacing: 0.0,
runSpacing: 0,
maxMainAxisCount: 3,
minMainAxisCount: 3,
padding: const EdgeInsets.all(5),
children: <Widget>[
MyCard(
model: models[0],
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => FakePage(model: models[0]),
),
),
),
MyCard(
model: models[1],
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => FakePage(model: models[1]),
),
),
),
MyCard(
model: models[2],
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => FakePage(model: models[2]),
),
),
),
MyCard(
model: models[3],
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => FakePage(model: models[3]),
),
),
),
MyCard(
model: models[4],
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => FakePage(model: models[4]),
),
),
),
MyCard(
model: models[5],
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => FakePage(model: models[5]),
),
),
),
MyCard(
model: models[6],
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => FakePage(model: models[6]),
),
),
),
MyCard(
model: models[7],
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => FakePage(model: models[7]),
),
),
),
MyCard(
model: models[8],
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => FakePage(model: models[8]),
),
),
),
],
onReorder: _onReorder,
onNoReorder: (int index) {
//this callback is optional
debugPrint('${DateTime.now().toString().substring(5, 22)} ' +
'reorder cancelled. index:$index');
},
onReorderStarted: (int index) {
//this callback is optional
debugPrint('${DateTime.now().toString().substring(5, 22)} ' +
'reorder started: index:$index');
});
}
}
// ---------------------- Model --------------------------
class Model {
int index;
String title;
Icon icon;
Model({this.index, this.title, this.icon});
#override
String toString() {
return '$index : $title';
}
}
// ------------------------ MyCard ----------------------------
class MyCard extends StatelessWidget {
final Model model;
final void Function() onTap;
const MyCard({Key key, this.onTap, #required this.model})
: assert(model != null),
super(key: key);
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return GestureDetector(
onTap: onTap,
child: Card(
elevation: 8.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
child: _child(width),
),
);
}
Widget _child(double width) {
return Container(
width: width / 4,
height: width / 3,
margin: EdgeInsets.all(5.0),
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
flex: 3,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
model.title,
maxLines: 1,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 15.0,
),
overflow: TextOverflow.ellipsis,
),
Icon(
Icons.arrow_forward_ios,
color: Colors.grey.shade400,
size: 15.0,
),
],
),
),
Expanded(
flex: 5,
child: Padding(
padding: EdgeInsets.all(8.0),
child: FittedBox(
fit: BoxFit.contain,
child: model.icon,
),
),
),
],
),
);
}
}
// ----------------------- FAKE PAGE ---------------------------
class FakePage extends StatelessWidget {
final Model model;
const FakePage({Key key, this.model}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.deepOrangeAccent,
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'You Clicked on Card : ${model.title}',
style: TextStyle(fontSize: 20.0),
),
Padding(
padding: EdgeInsets.only(top: 24.0),
child: Icon(
model.icon.icon,
size: 70.0,
),
),
],
),
),
);
}
}

How do I build objects of a class to use in ListView.builder?

I made a class of cars (has multiple strings such as price and brand.. etc) and I am trying to build a list of it so I can use it when building cards in a ListView but nothing shows up in the screen when I run the code.
I get an error that says vertical viewport was given unbounded height and my app does not show any cards (it does show anything else on the screen though)
My class:-
class cars {
String brand, type, model, color, price, pic;
cars(String b, String t, String m, String c, String p1, String p2) {
brand = b;
type = t;
model = m;
color = c;
price = p1;
pic = p2;
}
}
(page class)
class CHomePage extends State<CHP> {
int i = 0;
String price;
int selected = 0;
List<String> prices = ["Any", "<= 1200", "<= 1600", "<= 1800", "<= 2000"];
List<cars> myCars = new List();
void carsBuilder() {
cars c = new cars(
"Chevorlet", "Corvette Stingray", "2019", "Turqoise", "\$2100",
"assets/Images/corvette.jpg");
myCars.add(c);
c = new cars("Chevorlet", "Impala", "1967", "Black", "\$1900",
"assets/Images/impala.jpg");
myCars.add(c);
c = new cars(
"Dodge", "Challenger SRT Hellcat", "1967", "Dark Red", "\$2000",
"assets/Images/challenger.jpg");
myCars.add(c);
}
Widget buildPicker() {
return CupertinoPicker(
itemExtent: 50,
backgroundColor: CupertinoColors.white,
onSelectedItemChanged: (index) {
setState(() {
selected = index;
});
},
children: List<Widget>.generate(
prices.length,
(index) {
return Center(
child: Text(
prices[index],
style: TextStyle(fontSize: 18, color: Color(0xff469ABF)),
),
);
},
));
}
void incrementTab(index) {
setState(() {
i = index;
if (i == 1) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CAP()),
);
} else if (i == 2) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LP()),
);
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: CupertinoNavigationBar(
middle: Text(
'Home Page',
style: TextStyle(color: Color(0xff469ABF)),
),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Padding(
padding: EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
"Choose Price Range: ",
style: TextStyle(fontSize: 18, color: Color(0xff469ABF)),
),
new CupertinoButton(
onPressed: () async {
await showModalBottomSheet<int>(
context: context,
builder: (BuildContext context) {
return buildPicker();
},
);
},
child: Text(prices[selected]),
),
],
),
),
new ListView.builder(
itemCount: myCars.length,
itemBuilder: (context, index) {
return Card(
child: Column(
children: <Widget>[
new ListTile(
leading: Icon(Icons.directions_car),
title: Text(myCars[index].type),
subtitle: Text(myCars[index].price),
),
new ButtonTheme.bar(
child: ButtonBar(
children: <Widget>[
new CupertinoButton(
child: Text("View More Details"),
onPressed: () {},
),
],
),
),
],
),
);
},
),
],
),
),
bottomNavigationBar: new Theme(
data: Theme.of(context).copyWith(
primaryColor: Colors.lightBlue,
textTheme: Theme.of(context)
.textTheme
.copyWith(caption: new TextStyle(color: Colors.black))),
child: new BottomNavigationBar(
items: [
BottomNavigationBarItem(
title: new Text('Home'),
icon: Icon(Icons.home),
),
BottomNavigationBarItem(
title: new Text('Account'),
icon: Icon(Icons.person),
),
BottomNavigationBarItem(
title: new Text('Logout'),
icon: Icon(Icons.directions_run),
),
],
currentIndex: i,
onTap: (index) {
incrementTab(index);
},
),
),
);
}
}
UPDATE:-
I added those 2 lines to my ListView.builder:-
scrollDirection: Axis.vertical,
shrinkWrap: true,
and put the parent column inside a listview and made the builder a child of it instead of being a child to the column..
My items show and i can scroll ONLY when i press somewhere specific.. other than that it doesnt scroll..
https://gyazo.com/f221fe659df002032ef7b56af5da4a56
where are you initializing the cars list
#override
void initState() {
// TODO: implement initState
super.initState();
carsBuilder();
}

onTap go to next list item (Flutter)

I have a ListView.builder showing a list, when i click on an item it shows details of that item on the next page (FlashcardDetailsPage).
I'd like to show the next list item when i tap the IconButton in the class FlashcardDetailsPage. So i'd like this button to skip to the next list item. Any ideas?
class FlashcardListView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: allFlashcards.length,
itemBuilder: (context, int index) {
return ListTile(
title: Text(allFlashcards[index].actReg),
subtitle: Text(allFlashcards[index].question),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FlashcardDetailPage(
flashcardToShow: allFlashcards[index]),
),
);
},
);
});
}
}
class FlashcardDetailPage extends StatefulWidget {
final Flashcard flashcardToShow;
FlashcardDetailPage({Key key, #required this.flashcardToShow})
: super(key: key);
#override
_FlashcardDetailPageState createState() => _FlashcardDetailPageState();
}
class _FlashcardDetailPageState extends State<FlashcardDetailPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromRGBO(242, 242, 242, 1),
appBar: AppBar(
centerTitle: true,
title: Text(widget.flashcardToShow.actReg),
),
body: Column(
children: <Widget>[
Container(
child: Card(
margin: EdgeInsetsDirectional.fromSTEB(20, 20, 20, 0),
child: Center(
child: Text(
widget.flashcardToShow.question,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 30),
),
)),
),
Container(
height: 100.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
icon: Icon(Icons.skip_next),
iconSize: 32.0,
),
],
),
),
],
),
);
}
}
You could just replace the screen with another one showing the next card:
IconButton(
icon: Icon(Icons.skip_next),
iconSiz: 32,
onTap: () {
int currentIndex = allFlashcards.indexOf(widget.flashcardToShow);
if (currentIndex >= allFlashcards.length) return;
var nextFlashcard = allFlashcards[currentIndex + 1];
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (ctx) => FlashDetailsPage(flashcardToShow: nextFlashcard)
));
},
)
Thanks Marcel for the direction! I used your logic for a method. To avoid opening a new page every time I pressed the button, i did this & it's working:
void _skipFlashcard () {
setState(() {
int currentIndex = allFlashcards.indexOf(widget.flashcardToShow);
var nextFlashcard = allFlashcards[currentIndex + 1];
widget.flashcardToShow = nextFlashcard;
});
}
IconButton(
icon: Icon(Icons.skip_next),
iconSize: 32.0,
onPressed: _skipFlashcard,