I want to use bottomNavigationBar with listview, I tried each one of them separately and they work fine, but when I use them together, the bottomNavigationBar doesn't work, you can press the icons but nothing happens.
note: I'm using an older version of dart to avoid null-safety which is dumb, but the reason is the book I read is from 2019 so I couldn't follow without using an older version.
note 2: I'm very new to programming.
main.dart
//#dart=2.9
import 'package:flutter/material.dart';
import 'package:ch8_bottom_navigation/pages/home.dart';
void main() => runApp(Myapp());
class Myapp extends StatelessWidget {
//this widget is the root of the app
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Starter Template',
theme: ThemeData (
primarySwatch: Colors.blue,
platform: TargetPlatform.iOS,
),
home: Home(),
);
}
}
home.dart
//#dart=2.9
import 'package:flutter/material.dart';
import 'discover.dart';
import 'home2.dart';
import 'account.dart';
class Home extends StatefulWidget {
const Home({Key key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _currentIndex = 0;
List _listPages = [];
Widget _currentPage;
#override
void initState() {
super.initState();
_listPages
..add(Home2())
..add(Discover())
..add(Account());
_currentPage = Discover();
}
void _changePage(int selectedIndex) {
setState(() {
_currentIndex = selectedIndex;
_currentPage = _listPages[selectedIndex];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView.builder(
itemCount:20 ,
itemBuilder: (BuildContext context , int index) {
if (index >= 0 && index <= 0) {
return Home2 (index:index);
}
else return null;
},
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.live_tv),
label: ('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.explore_outlined),
label: ('Discover'),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_box_outlined),
label: ('Account'),
),
],
onTap: (selectedIndex) => _changePage(selectedIndex),
),
);
}
}
home2.dart
//#dart=2.9
import 'package:flutter/material.dart';
class Home2 extends StatelessWidget {
const Home2({Key key , #required this.index}) : super(key: key);
final int index;
#override
Widget build(BuildContext context) {
return Container(
child:Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
color: Colors.white70,
child: ListTile(
leading: Image(
image: AssetImage('assets/images/blackwidow.jpg'),
),
title: Text('Black Widow'),
subtitle: Text('By Disney'),
trailing: Icon(Icons.movie),
selected: true,
onTap: () {
print('Trapped on Row $index');
},
),
)
);
}
}
body: SafeArea(child: _currentPage),
or
body: SafeArea(child: _listPages[selectedIndex]),
Did you try this way?
Related
I'm currently playing around with flutter by recreating the google files app. I followed some tutorials and stuff but are now stuck at a problem I can't find a solution for. I want the bottomNavigationBar to extend behind the systemNavigationBar which I made transparent.
The left image is my flutter app, the right one is the real deal.
Here's the code for that so far:
void main() {
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
systemNavigationBarColor: Colors.transparent));
runApp(const Main());
}
class Main extends StatelessWidget {
const Main({Key? key}) : super(key: key);
static const _brandColor = Colors.blue;
#override
Widget build(BuildContext context) {
// Wrap MaterialApp with a DynamicColorBuilder.
return DynamicColorBuilder(
builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
ColorScheme lightColorScheme;
ColorScheme darkColorScheme;
if (lightDynamic != null && darkDynamic != null) {
lightColorScheme = lightDynamic.harmonized();
darkColorScheme = darkDynamic.harmonized();
} else {
lightColorScheme = ColorScheme.fromSeed(
seedColor: _brandColor,
);
darkColorScheme = ColorScheme.fromSeed(
seedColor: _brandColor,
brightness: Brightness.dark,
);
}
return MaterialApp(
theme: ThemeData(
colorScheme: lightColorScheme,
useMaterial3: true,
),
darkTheme: ThemeData(
colorScheme: darkColorScheme,
useMaterial3: true,
),
home: const RootPage(),
debugShowCheckedModeBanner: false,
);
},
);
}
}
class RootPage extends StatefulWidget {
const RootPage({Key? key}) : super(key: key);
#override
State<RootPage> createState() => _RootPageState();
}
class _RootPageState extends State<RootPage> {
int currentPage = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Title'),
),
body: const HomePage(),
floatingActionButton: FloatingActionButton(
onPressed: () {
debugPrint("Button pressed");
},
child: const Icon(Icons.add),
),
bottomNavigationBar: NavigationBar(
destinations: const [
NavigationDestination(icon: Icon(Icons.home_filled), label: "Start"),
NavigationDestination(
icon: Icon(Icons.star_outline), label: "Markiert"),
NavigationDestination(
icon: Icon(Icons.people_alt_outlined), label: "Freigegeben"),
NavigationDestination(
icon: Icon(Icons.folder_open_outlined), label: "Dateien"),
],
onDestinationSelected: (int i) {
setState(() {
currentPage = i;
});
},
selectedIndex: currentPage,
),
);
}
}
In this code, I want to show indexed widgets by changing the index from the Navigation drawer i.e. The main MaterialApp shows widget according to the index(widgetIndex). The index is updated but the widget does not change until I hot reload it. So, I want it to reload the MyApp widget from the drawer widget.
main.dart:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:indexed/page1.dart';
import 'package:indexed/page2.dart';
import 'drawer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
//set widgetIndex(int widgetIndex) {widgetIndex = DrawerS.widgetIndex;}
int widgetIndex = SideDrawerState.widgetIndex;
#override
Widget build(BuildContext context)
{
return MaterialApp(
home: Container(
child: IndexedStack(
index: widgetIndex,
children: <Widget>[
Page1(), //A Scaffold wid.
Page2(), //A Scaffold wid.
],
),
),
);
}
}
drawer.dart:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class SideDrawer extends StatefulWidget {
#override
SideDrawerState createState() => SideDrawerState();
}
class SideDrawerState extends State<SideDrawer> {
static int widgetIndex = 0;
#override
Widget build(BuildContext context) {
return Drawer(
child: Column(
children: <Widget>[
ListTile(
contentPadding: EdgeInsets.only(top: 50),
title: Text('1'),
onTap: () async {
setState(() => widgetIndex = 0);
Navigator.of(context).pop();
},
),
ListTile(
title: Text('2'),
onTap: (){
setState(() => widgetIndex = 1);
Navigator.of(context).pop();
},
),
],
),
);
}
}
You can create a function field in your SideDrawer that takes an index as a parameter.
Call the function passing the appropriate parameter in the onTap of each ListTile.
In your MyApp create a variable with initial value of 0 then when setting the SideDrawer add the onTap attribute then change the value of the in the setState
Like this
class MyApp2 extends StatefulWidget {
#override
MyApp2State createState() => MyApp2State();
}
class MyApp2State extends State<MyApp2> {
var widgetIndex = 0;
#override
Widget build(BuildContext context)
{
return Scaffold(
appBar: AppBar(
title: Text("Home"),
),
body: SafeArea(
child: Container(
child: IndexedStack(
index: widgetIndex,
children: <Widget>[
Text("djdhjhd"),
Text("nonono")
],
),
),
),
drawer: SideDrawer(
onTap: (index){
setState(() {
widgetIndex = index;
});
},
),
);
}
}
class SideDrawer extends StatefulWidget {
final Function(int index) onTap;
SideDrawer({this.onTap});
#override
SideDrawerState createState() => SideDrawerState();
}
class SideDrawerState extends State<SideDrawer> {
#override
Widget build(BuildContext context) {
return Drawer(
child: Column(
children: <Widget>[
ListTile(
contentPadding: EdgeInsets.only(top: 50),
title: Text('1'),
onTap: () async {
widget.onTap(0);
Navigator.of(context).pop();
},
),
ListTile(
title: Text('2'),
onTap: (){
widget.onTap(1);
Navigator.of(context).pop();
},
),
],
),
);
}
}
The output:
I hope this helps you.
Here is my class
class Home extends StatelessWidget {
and the Checkbox goes here.
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
TextField(
controller: ctrlMotherName,
decoration: InputDecoration(
labelText: "Name of Mother",
border: OutlineInputBorder()
)
),
SizedBox(height: 10,),
Checkbox(
value: false,
onChanged: (bool val){
},
),
I can't able to check the checkbox. Same issue found when I use Radiobutton also.
You need to use a StatefulWidget since you're dealing with changing values. I've provided an example:
class MyAppOne extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyAppOne> {
bool _myBoolean = false;
#override
Widget build(BuildContext context) {
return Center(
child: Checkbox(
value: _myBoolean,
onChanged: (value) {
setState(() {
_myBoolean = value; // rebuilds with new value
});
},
),
);
}
}
One way you can achieve this is using the provider package. I tried to create the shortest possible app to show how you can use it. The neat part is that you get to keep your widget stateless.
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Home(),
);
}
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ChangeNotifierProvider(
create: (_) => CheckboxProvider(),
child: Consumer<CheckboxProvider>(
builder: (context, checkboxProvider, _) => Checkbox(
value: checkboxProvider.isChecked,
onChanged: (value) {
checkboxProvider.isChecked = value ?? true;
},
),
),
),
),
);
}
}
class CheckboxProvider with ChangeNotifier {
bool _isChecked = false;
bool get isChecked => _isChecked;
set isChecked(bool value) {
_isChecked = value;
notifyListeners();
}
}
It took me quite some time to understand the package but it is very useful and recommended if you want an easier way to manage state in your application. Here's a video from the Flutter team explaining how to use Provider. I would still recommend spending some time looking further into it.
P.S.: Don't forget to change the pubspec.yaml file.
think of flutter like javascript and pass the position as a parameter to the medCheckedChanged function in the list builder. when the dart parser evaluates the expression or lambda function it will invoke the method with the position parameter as a value.
class testWidget2 extends StatefulWidget {
testWidget2({Key key}) : super(key: key);
int numberLines = 50;
List<bool> checkBoxValues = [];
#override
_testWidget2State createState() => _testWidget2State();
}
class _testWidget2State extends State<testWidget2> {
_medCheckedChanged(bool value, int position) {
setState(() => widget.checkBoxValues[position] = value);
}
#override
void initState() {
// TODO: implement initState
super.initState();
int i = 0;
setState(() {
while (i < widget.numberLines) {
widget.checkBoxValues.add(false);
i++;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: ListView.builder(
itemCount: widget.checkBoxValues.length,
itemBuilder: (context, position) {
return Container(
height: MediaQuery.of(context).size.width * .06,
width: MediaQuery.of(context).size.height * .14,
alignment: Alignment(0, 0),
child: Checkbox(
activeColor: Color(0xff06bbfb),
value: widget.checkBoxValues[position],
onChanged: (newValue) {
_medCheckedChanged(newValue, position);
}, //pass to medCheckedChanged() the position
),
);
})));
}
}
You can use StateProvider from the Riverpod package to achieve this.
final checkboxProvider = StateProvider<bool>((ref) => false);
class CheckboxWidget extends StatelessWidget {
const CheckboxWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
children: [
Consumer(
builder: (context, ref, _) {
return Checkbox(
value: ref.watch(checkboxProvider),
onChanged: (value) {
ref.read(checkboxProvider.state).state = value!;
},
);
}
),
Text('On'),
],
);
}
}
Hi Im new to flutter so please bear with me for asking too much nooby question. So I am currently developing an app, the first screen will be a Login/register screen then after a login or registration is directed, the actual main app screen is displayed I also set this screen as stateless and set a body to my HomePage.dart now on my HomePage.dart which is a stateful widget, which contains the navigation bar but for some reason, Im getting an error in
final List<Widget> _children [
NavHome()
];
saying that the children is initialized. And Im confused since I followed the tutorial from medium exactly BUT with just a custom main screen (which appears after the main.dart)
the code for the actual main app screen is below:
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'home.dart';
class MainScreen extends StatelessWidget {
const MainScreen({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: HomePage(),
);
}
}
the code for Home.dart is below which says the children variable isnt initialized
import 'package:flutter/material.dart';
import 'package:vmembershipofficial/screens/nav_home.dart';
class HomePage extends StatefulWidget {
static final String id = 'homepage';
HomePage({Key key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _currentTab = 2;
final List<Widget> _children [
NavHome()
];
void onTabTapped(int index) {
setState(() {
_currentTab = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _children[_currentTab],
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped,
type: BottomNavigationBarType.fixed,
currentIndex: _currentTab, //makes a new variable called current Tab
items: [
BottomNavigationBarItem(
icon: Icon(Icons.search, size: 30.0),
title: Text('Search', style: TextStyle(fontSize: 12.0),),
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
title: Text('Favorites', style: TextStyle(fontSize: 12.0),),
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home', style: TextStyle(fontSize: 12.0),),
),
BottomNavigationBarItem(
icon: Icon(Icons.message),
title: Text('Messages', style: TextStyle(fontSize: 12.0),),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Text('Account', style: TextStyle(fontSize: 12.0),),
),
],
),
);
}
}
NOTE: I just want the bottom navigation bar to change to the NavHome, or NavProfile when I tapped on different tabs. I just cant seem to find a way why the _children variable isnt initialized.
You're almost there!
What went wrong
final List<Widget> _children [ // Missing = sign
NavHome()
];
What you can do
Convert the code snippet above to:
final List<Widget> _children = [ // Add = sign here
NavHome(),
NavProfile(),
// Add more screens here
];
I created a simple app for you, which mocks your use case that you need to switch between NavHome and NavProfile.
main.dart
import 'package:flutter/material.dart';
void main() => runApp(ExampleApp());
class ExampleApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Example App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
static final String id = 'homepage';
HomePage({Key key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _currentTab = 0;
final List<Widget> _children = [
RedPage(),
BluePage(),
];
void onTabTapped(int index) {
setState(() {
_currentTab = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _children[_currentTab],
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped,
type: BottomNavigationBarType.fixed,
currentIndex: _currentTab,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
title: Text(
'Red',
style: TextStyle(fontSize: 12.0),
),
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text(
'Blue',
style: TextStyle(fontSize: 12.0),
),
),
],
),
);
}
}
class RedPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.red,
),
);
}
}
class BluePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.blue,
),
);
}
}
I have also noticed that you have 5 widgets in your bottom navigation bar, feel free to add placeholders so you won't get RangeError exception whenever you tap on tabs without the counterpart screen/s.
Hope this helps.
I am building an app and in it, I have the names of people in a list from which I could add/delete, etc.. The problem is this list is not saved when I close the app, which is inconvenient.
I heard you can use shared Preferences to save simple objects like this, without complicating things like using SQLite and json.
So I'd like to know what's the suggested way to persist this data and load it etc.
Thanks in Advance and have a great day :)
Here is the code:
import 'package:flutter/material.dart';
import 'package:zakif_yomi3/NewPerson.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.purple,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<String> people = [];
void _addNewPerson(String name) {
setState(() {
people.add(name);
});
}
void _startAddNewPerson(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewPerson(_addNewPerson),
behavior: HitTestBehavior.opaque,
);
},
);
}
void _deletePerson(int value ) {
setState(() {
people.removeAt(value);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
'People',
style: TextStyle(fontSize: 30),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewPerson(context),
)
],
),
body: ListView.builder(
itemCount: this.people.length,
itemBuilder: (context, value) {
return Card(
color: Colors.amberAccent[200],
elevation: 3,
child: Container(
child: ListTile(
leading: Text(value.toString()),
title: Text(
people[value],
),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
_deletePerson(value);
},
),
),
),
);
},
),
);
}
}
And the NewPerson object:
import 'package:flutter/material.dart';
class NewPerson extends StatefulWidget {
final Function addTx;
NewPerson(this.addTx);
#override
_NewPersonState createState() => _NewPersonState();
}
class _NewPersonState extends State<NewPerson> {
final _nameController = TextEditingController();
void _submitData() {
final name = _nameController.text;
widget.addTx(
name
);
Navigator.of(context).pop();
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Name'),
controller: _nameController,
onSubmitted: (_) => _submitData(),
),
RaisedButton(
child: Text('Add Person'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button.color,
onPressed: _submitData,
),
],
),
),
);
}
}
You could use this functions to persist and load data from shared preferences.
Get SharedPreferences from here.
To persist data to SharedPreferences, called after adding or deleting a new element to the list.
_persistData() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.setStringList("persons", _people);
}
To load data from SharedPreferences, usually called in initState.
_loadData() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
_people = preferences.getStringList("persons");
});
}