Updating part of a stateful widget - flutter

i'm very new to Flutter.
I have a stateful widget. Every time i click a counter, the whole build function runs and the results are updated.
But is there a way to make it a stateless widget and update only the relevant part somehow so i could avoid rebuilding the screen?
I have a stateful widget. Every time i click a counter, the whole build function runs and the results are updated.
But is there a way to make it a stateless widget and update only the relevant part somehow so i could avoid rebuilding the screen?
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home:Home(),
));
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State {
int long = 0;
void increaseCounter(){
setState(() {
long++;
});
}
void decreaseCounter(){
if(long > 0) {
setState(() {
long--;
});
}
}
Text numberOfDeliveries(){
return Text(
'$long deliveries today',
style: TextStyle(
color:Colors.white,
fontSize: 24.0,
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text('Deliveries'),
backgroundColor: Colors.green,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Container(
color: Colors.blue,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child:Padding(
padding: const EdgeInsets.symmetric(vertical: 32.0, horizontal: 0.0),
child: Text(
'Long',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 32.0,
color: Colors.white,
),
),
),
),
Expanded(
child:
// is it possible to update this without running the whole build again?
numberOfDeliveries(),
),
Expanded(
child: Row(
children: [
Expanded(
child: Container(
padding: EdgeInsets.symmetric(vertical: 32.0, horizontal: 0.0),
color:Colors.blue[100],
child: FlatButton(
onPressed: (){
decreaseCounter();
},
child: Text('-'),
),
),
),
Expanded(
child: Container(
padding: EdgeInsets.symmetric(vertical: 32.0, horizontal: 0.0),
color:Colors.blue[500],
),
),
Expanded(
child: Container(
padding: EdgeInsets.symmetric(vertical: 32.0, horizontal: 0.0),
color:Colors.blue[900],
child: FlatButton(
onPressed: (){
increaseCounter();
},
child: Text('+'),
),
),
),
],
),
),
],
),
),
),
Expanded(
child: Container(
color: Colors.blue[800],
child: Row(
children: [
Text('Bottom'),
],
),
),
),
],
),
);
}
}

Related

Flutter: How can i put the text widget center in screen

I need to put the title' in the center even to fit any screen, I know can I sized box to move the title in the center, but when using the different device the dimensions surely will change and become the title the different places.
this is code :
class NotificationDoctor extends StatelessWidget {
TextStyles textStyles = TextStyles.HEADING;
Texts texts;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColorDark,
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(15.0))),
height: 130.h,
child: Padding(
padding: EdgeInsets.only(top: 40.h),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.only(
right: 15.w,
top: 15.h,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
FlatButton(
child: ArrowIcon(
arrowColor: Color(0xFFEEF4F9),
backgroundColor:
Theme.of(context).primaryColor.withOpacity(.9),
),
onPressed: () {
Navigator.pop(context);
},
),
// SizedBox(
// width: 55,
// ),
Center(
child: Texts(
'Notifications',
style: TextStyles.HEADING,
color: Color(0xFFEEF4F9),
),
),
],
),
),
],
),
),
),
));
}
}
use the padding like this
Padding(
padding: EdgeInsets.symmetric(vertical: 5.h, horizontal: 3.h),
child: Container(),
);
read more at https://pub.dev/packages/sizer

Flutter UI adjacent placement problem and List View Height

I am trying to show some data from the database and my app must contain UI like this.
But I am encountering this kind of problem.
Problems:
The text is overflowing and not wrapping (I tried to use Flexible and Expanded but it produces more exceptions, mostly of non-zero flex and so on)
The list needs fixed height and width, whereas I need height to match_parent. double.infinity don't work as well.
Here is my code:
class CategoryDetailPage extends StatefulWidget {
final Category category;
CategoryDetailPage({Key key, this.category}) : super(key: key);
#override
_CategoryDetailPageState createState() => _CategoryDetailPageState();
}
class _CategoryDetailPageState extends State<CategoryDetailPage> {
DatabaseProvider databaseProvider = DatabaseProvider.instance;
List<Phrase> phrases;
final List<Color> _itemColors = [
Color(0xff16a085),
Color(0xff2980b9),
Color(0xff8e44ad),
Color(0xff2c3e50),
Color(0xffd35400),
Color(0xffbdc3c7),
Color(0xff27ae60),
Color(0xfff39c12),
Color(0xff7f8c8d),
Color(0xffc0392b),
];
int _colorCounter = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Row(
children: [
Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image(
image: AssetImage("assets/images/categories/${widget.category.image}"),
width: 32,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Say ${widget.category.name}",
style: TextStyle(fontSize: 24, fontFamily: "Pacifico"),
),
Text(
"\"${widget.category.quote}\" --${widget.category.quoteAuthor} aaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey,
fontStyle: FontStyle.italic
),
),
],
),
),
],
),
Row(
children: <Widget>[
RotatedBox(
quarterTurns: -1,
child: Column(
children: <Widget>[
Text(
"Informal",
style: TextStyle(
fontSize: 32,
color: Colors.grey.withOpacity(0.5),
fontFamily: "AbrilFatFace"),
),
],
),
),
Container(
height: 300,
width: 300,
child: FutureBuilder(
future: databaseProvider
.getPhrasesByCategoryId(widget.category.id),
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, i) {
return _buildPhraseItem(snapshot.data[i]);
})
: Center(
child: CircularProgressIndicator(),
);
},
),
),
],
),
],
),
),
),
);
}
Widget _buildPhraseItem(Phrase phrase) {
Random random = Random();
int colorIndex = random.nextInt(_itemColors.length - 1);
Color currentColor = _itemColors[colorIndex];
if (_colorCounter >= 10) _colorCounter = 0;
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PhraseDetail(
phraseToShow: phrase.phrase,
color: currentColor,
)));
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 80,
decoration: BoxDecoration(
color: currentColor,
borderRadius: BorderRadius.all(Radius.circular(4)),
boxShadow: [
BoxShadow(
blurRadius: 8,
color: Colors.grey.withOpacity(0.5),
offset: Offset(0, 3))
]),
child: Center(
child: Text(
phrase.phrase,
style: TextStyle(color: Colors.white),
)),
),
),
);
}
}
wrap the second child(Padding) of the first Row with Flexible
wrap the second child(Container) of the second Row with Flexible and remove width: 300 from the container parameters.
import 'dart:math';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CategoryDetailPage(),
);
}
}
Random random = Random();
class CategoryDetailPage extends StatefulWidget {
CategoryDetailPage({
Key key,
}) : super(key: key);
#override
_CategoryDetailPageState createState() => _CategoryDetailPageState();
}
class _CategoryDetailPageState extends State<CategoryDetailPage> {
final List<Color> _itemColors = [
Color(0xff16a085),
Color(0xff2980b9),
Color(0xff8e44ad),
Color(0xff2c3e50),
Color(0xffd35400),
Color(0xffbdc3c7),
Color(0xff27ae60),
Color(0xfff39c12),
Color(0xff7f8c8d),
Color(0xffc0392b),
];
int _colorCounter = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.min,
// crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image(
image: NetworkImage(
'https://source.unsplash.com/random',
),
width: 32,
),
),
),
Flexible(
child: Padding(
padding: const EdgeInsets.only(left: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'say congratulations',
style:
TextStyle(fontSize: 24, fontFamily: "Pacifico"),
),
Text(
"At every party there are two kinds of people – those who want to go home and those who don’t. The trouble is, they are usually married to each other. - Ann Landers",
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey,
fontStyle: FontStyle.italic),
),
],
),
),
),
],
),
Row(
children: <Widget>[
RotatedBox(
quarterTurns: -1,
child: Column(
children: <Widget>[
Text(
"Informal",
style: TextStyle(
fontSize: 32,
color: Colors.grey.withOpacity(0.5),
fontFamily: "AbrilFatFace"),
),
],
),
),
Flexible(
child: Container(
height: 300,
child: ListView(children: [
_buildPhraseItem(),
_buildPhraseItem(),
_buildPhraseItem(),
_buildPhraseItem(),
]),
),
),
],
),
],
),
),
),
);
}
Widget _buildPhraseItem() {
var colorIndex = random.nextInt(_itemColors.length - 1);
var currentColor = _itemColors[colorIndex];
if (_colorCounter >= 10) _colorCounter = 0;
return InkWell(
onTap: () {
print('Navigator.push');
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 80,
decoration: BoxDecoration(
color: currentColor,
borderRadius: BorderRadius.all(Radius.circular(4)),
boxShadow: [
BoxShadow(
blurRadius: 8,
color: Colors.grey.withOpacity(0.5),
offset: Offset(0, 3))
]),
child: Center(
child: Text(
'phrase.phrase',
style: TextStyle(color: Colors.white),
)),
),
),
);
}
}

flutter setState isn't defined

I have a Widget to create a sidebar menu:
Widget dashboard(context) {
return Material(
elevation: 8,
color: backgroundColor,
child: Container(
padding: const EdgeInsets.only(left: 16, right: 16, top: 48),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
InkWell(child: Icon(Icons.menu, color: Colors.white), onTap: () {
setState(() {
isCollapsed = !isCollapsed;
});
},),
Text("Corona App", style: TextStyle(fontSize: 24.0, color: Colors.white)),
Icon(Icons.settings, color: Colors.white),
])
],
),
)
);
}
But I keep getting the error that my setState function isn't defined. My main app is a statefullwidget so this is pretty weird. Can anyone help me?
Here is the full code!
import 'package:flutter/material.dart';
final Color backgroundColor = Color(0xFF4A4A58);
class MenuDashboard extends StatefulWidget {
#override
_MenuDashboardState createState() => _MenuDashboardState();
}
class _MenuDashboardState extends State<MenuDashboard> {
bool isCollapsed = true;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: backgroundColor,
body: Stack(
children: <Widget>[
menu(context),
dashboard(context),
],
),
);
}
}
Widget menu(context) {
return Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Align(
alignment: Alignment.centerLeft,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Home", style: TextStyle(color: Colors.white, fontSize: 20),),
SizedBox(height: 10.0),
Text("Brochures", style: TextStyle(color: Colors.white, fontSize: 20),),
SizedBox(height: 10.0),
Text("Visitekaartje", style: TextStyle(color: Colors.white, fontSize: 20),),
SizedBox(height: 10.0),
]
)
)
);
}
Widget dashboard(context) {
return Material(
elevation: 8,
color: backgroundColor,
child: Container(
padding: const EdgeInsets.only(left: 16, right: 16, top: 48),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
InkWell(child: Icon(Icons.menu, color: Colors.white), onTap: () {
setState(() {
isCollapsed = !isCollapsed;
});
},),
Text("Corona App", style: TextStyle(fontSize: 24.0, color: Colors.white)),
Icon(Icons.settings, color: Colors.white),
])
],
),
)
);
}
with the error message: 'The function setState isn't defined'
setState is a member of State class, which means it can only be called inside a class that extends a State class of a StatefulWidget. If your class is extending StatelessWidget, you can't called state members/methods provided by the super class, including setState, initState and dispose methods.
For the answer, you can't call setState outside of the State class, if possible, put the widget methods inside the class, or pass setState function as a parameter to those methods.
setState can only called inside StatefulWidget. So if I got it right, you use setState in Widget dashboard or menu widgets. It can't work, because those widgets in outside of class. Try to put widgets inside the class

Flutter - material design 2 semi transparent appbar

I want to get effect like this - when scrolled up, appbar is transparent with listview visible below it:
And scrolled down, only white color - first item below appbar:
My window layout:
return Container(
color: AppTheme.nearlyWhite,
child: SafeArea(
top: false,
bottom: false,
child: Scaffold(
backgroundColor: AppTheme.nearlyWhite,
body: Stack(
children: <Widget>[
DrawerUserController(
screenIndex: _drawerIndex,
drawerWidth: MediaQuery.of(context).size.width * 0.75,
animationController: (AnimationController animationController) => _sliderAnimationController = animationController,
onDrawerCall: (DrawerIndex drawerIndexdata) => _onDrawerCall(drawerIndexdata, _forceRefresh),
onDrawerTap:(DrawerIndex drawerIndexdata) => _onDrawerTap(drawerIndexdata),
screenView: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(8, MediaQuery.of(context).padding.top + 8, 8, 8),
child: _createAppBar(),
),
Expanded(
child:
Container(
color: Colors.white,
child: _screenView,
)
),
],
),
),
new FabDialer(_fabMiniMenuItemList, Colors.blue, new Icon(Icons.add))
],
),
),
),
);
}
_screenView is simple Listview().builder() and it shows InkWell widget for each item. My appbar is custom, defined like this:
_createAppBar() {
return SizedBox(
height: AppBar().preferredSize.height,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 8, left: 8),
child: Container(
width: AppBar().preferredSize.height - 8,
height: AppBar().preferredSize.height - 8,
),
),
Expanded(
child: Center(
child: Padding(
padding: const EdgeInsets.only(top: 4),
child: Column(
children: <Widget>[
Text(
_menuSelected,
style: TextStyle(
fontSize: 22,
color: AppTheme.darkText,
fontWeight: FontWeight.w400,
),
),
Text(
globals.cityName,
style: TextStyle(
fontSize: 15,
color: AppTheme.darkerText,
fontWeight: FontWeight.w400,
),
),
],
),
),
),
),
Padding(
padding: const EdgeInsets.only(top: 8, right: 8),
child: Container(
width: AppBar().preferredSize.height - 8,
height: AppBar().preferredSize.height - 8,
color: Colors.white,
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius:
BorderRadius.circular(AppBar().preferredSize.height),
child: Icon(Icons.refresh, color: AppTheme.dark_grey,),
onTap: () => setState(() => _forceRefresh = true),
),
),
),
),
],
),
);
}
That's how it looks now with first list item visible:
So, almost there, but when scrolled down, appbar won't be transparent:
I tried to mess around with setting my appbar backround to color with transparency, without success. Also I need to get my widgets actually overlapped (ListView needs to overlap my appbar) and it generates error messages from Flutter.
Any ideas how to do that properly?
set extendBodyBehindAppBar: true in Scaffold widget. Then use Opacity widget like this,
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: Home()));
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight),
child: Opacity( //Wrap your `AppBar`
opacity: 0.8,
child: AppBar(
title: Text("Demo"),
),
),
),
body: ListView.builder(
itemCount: 30,
itemBuilder: (context, index) {
return ListTile(
title: Text("Tile: $index"),
);
},
),
);
}
}
#override
Widget build(BuildContext context) {
return Container(
child: Stack(
children:[
Container(
color:Colors.white,
padding:EdgeInsets.all(10),
child:ListView.builder(
itemCount:25+1,
//length + 1 is beacause to show 1st item at the beginning
shrinkWrap:true,
itemBuilder:(con,ind){
return ind==0 ?
Container(height:70)
:ListTile(
title:Text('Item $ind',
style:TextStyle(color:Colors.black,))
);
}
)
),
Container(
height:70,
color:Colors.transparent,
child:Card(
color:Colors.white.withAlpha(80),
child: Row(
children:[
Expanded(
flex:1,
child: IconButton(
icon:Icon(Icons.list,color:Colors.black,size:25),
onPressed:(){
//todo
}
),
),
Expanded(
flex:3,
child: Text('Title',
style:TextStyle(color:Colors.black,)),
),
Expanded(
flex:1,
child: IconButton(
icon:Icon(Icons.search,color:Colors.black,size:25),
onPressed:(){
//todo
}
),
),
Expanded(
flex:1,
child: IconButton(
icon:Icon(Icons.more_vert,color:Colors.black,size:25),
onPressed:(){
//todo
}
),
)
]
),
)
)
]
)
);
}

Flutter :-How to put the view in the Center and Bottom of the screen?

I am creating the tutorial screen in which the two views like:- one is should be in the center of the screen and another should at the bottom of the screen.
But my both view is not proper, please check the below images.
I have done some lines of the code to do it but the not getting the proper solution, please check below code once
import 'package:flutter/material.dart';
import 'package:page_indicator/page_indicator.dart';
import 'login_screen.dart';
class Tutorial extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _TutorialScreen();
}
}
class _TutorialScreen extends State<Tutorial> {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Align(
alignment: Alignment.center,
child:Column(
children: <Widget>[
Container(
height: 250.0,
margin: EdgeInsets.only(left: 10.0,top: 40.0,right: 10.0),
child: PageIndicatorContainer(
pageView: PageView(
children: <Widget>[
Container(
color: Colors.red,
),
Container(
color: Colors.yellow,
),
Container(
color: Colors.blueAccent,
)
],
),
length: 3,
align: IndicatorAlign.bottom,
indicatorSpace: 5.0,
padding: EdgeInsets.all(10.0),
),
),
Container(
height: 80.0,
color: Colors.purple,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
child: OutlineButton(
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => LoginScreen()));
},
textColor: Colors.white,
child: Text(
"Login",
style: TextStyle(color: Colors.white),
),
),
),
Container(
margin: EdgeInsets.only(left: 10.0),
child: RaisedButton(
onPressed: () {},
color: Colors.black54,
child:
Text("SignUp", style: TextStyle(color: Colors.white)),
),
),
],
),
)
],
)
),
);
}
}
Please check above code once and let me know once.
Use this to get required view
Stack(children: <Widget>[
Align(alignment: Alignment.center,
child: Container(width: 100, height: 100, color: Colors.redAccent,),),
Align(alignment: Alignment.bottomCenter,
child: Container(height: 100, color: Colors.purpleAccent,),)
],)
Put the bottom Container inside Align widget and use alignment: Alignment.bottomCenter .:
Align(
alignment: Alignment.bottomCenter,
child: Container(
height: 80.0,
color: Colors.purple,
child: Row(
... .... ... // other code
Thanks #Zulfiqar But It is not necessary to put the whole view inside the Stack widget and use the Align property with it.
We can also use the Expanded or flexible widget to come out from the problem.
We can also use the MediaQuery for it like below
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:page_indicator/page_indicator.dart';
class HomeScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _HomeScreen();
}
}
class _HomeScreen extends State<HomeScreen> {
#override
void initState() {
// TODO: implement initState
super.initState();
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Material(
child:Align(
alignment: Alignment.center,
child:Column(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height*0.90, /////HERE I USED MEDIAQUERY FOR IT
child: PageIndicatorContainer(
child: PageView(
children: <Widget>[
Container(
color: Colors.red,
),
Container(
color: Colors.yellow,
),
Container(
color: Colors.blueAccent,
)
],
),
length: 3,
align: IndicatorAlign.bottom,
indicatorSpace: 5.0,
padding: EdgeInsets.all(10.0),
),
),
Container(
height: MediaQuery.of(context).size.height*0.10, ////HERE I USED MEDIAQUERY FOR IT
color: Colors.purple,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
child: OutlineButton(
onPressed: () {
},
textColor: Colors.white,
child: Text(
"Login",
style: TextStyle(color: Colors.white),
),
),
),
Container(
margin: EdgeInsets.only(left: 10.0),
child: RaisedButton(
onPressed: () {},
color: Colors.black54,
child:
Text("SignUp", style: TextStyle(color: Colors.white)),
),
),
],
),
)
],
)
),
);
}
}
And for the pageView i have used this library page_indicator: ^0.3.0
And output from above code is as follow