Flutter counter not counting up - flutter

I have made this scorekeeper app for basketball. I need to count the score and show it on the application. But its stuck on 0. It probably has something to do with the setState().
If possible don't change the code too much since I need to show and explain this to my teacher.
inputPage:
class InputPage extends StatefulWidget {
#override
_InputPageState createState() => _InputPageState();
}
class _InputPageState extends State<InputPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('basketball counter'),
),
body: Column(
children: <Widget>[
Expanded(
child: Row(children: <Widget>[Expanded(child: HoopDesign()), Text(Counter.counter.toString())] ),
),
Expanded(
child: Row(
children: <Widget>[
Expanded(
child: CardDesign1(),
),
Expanded(
child: CardDesign3(),
),
Expanded(
child: CardDesign2(),
),
],
)),
Expanded(
child: Row(
children: <Widget>[
Expanded(
child: CardDesign6(),
),
Expanded(
child: CardDesign4(),
),
Expanded(
child: CardDesign5(),
),
],
),
),
Expanded(
child: Row(
children: <Widget>[
Expanded(
child: HoopDesign(),
),
],
),
),
],
),
);
}
}
Containers:
import 'package:flutter/material.dart';
import 'input_page.dart';
//#region Team1 cards
class CardDesign3 extends StatefulWidget {
#override
CardDesign3State createState() => CardDesign3State();
}
class CardDesign3State extends State<CardDesign3> {
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
},
child: Container(
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(0xFFEF7F4D),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'Vanaf de 3 punter lijn!',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Bullpen3D',
fontSize: 20,
),
),
height: 100,
width: 100,
));
}
}
class CardDesign2 extends StatefulWidget {
#override
_CardDesign2State createState() => _CardDesign2State();
}
class _CardDesign2State extends State<CardDesign2> {
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
setState(() => Counter.counter += 2);
},
child: Container(
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(0xFFEF7F4D),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'Vanaf de 2 punter lijn',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Bullpen3D',
fontSize: 20,
),
),
height: 100,
width: 100,
));
}
}
class CardDesign1 extends StatefulWidget {
#override
_CardDesign1State createState() => _CardDesign1State();
}
class _CardDesign1State extends State<CardDesign1> {
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
setState(() => Counter.counter++);
},
child: Container(
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(0xFFEF7F4D),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'Vanaf de 1 punter lijn',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Bullpen3D',
fontSize: 20,
),
),
height: 100,
width: 100,
));
}
}
//#endregion
//#region Team2 cards
class CardDesign4 extends StatefulWidget {
#override
CardDesign4State createState() => CardDesign4State();
}
class CardDesign4State extends State<CardDesign4> {
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
setState(() {
Counter2.counter += 3 ;
}
);
},
child: Container(
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(0xFFEF7F4D),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'Vanaf de 3 punter lijn!',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Bullpen3D',
fontSize: 20,
),
),
height: 100,
width: 100,
));
}
}
class CardDesign5 extends StatefulWidget {
#override
_CardDesign5State createState() => _CardDesign5State();
}
class _CardDesign5State extends State<CardDesign5> {
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
setState(() {
Counter2.counter += 2;
});
},
child: Container(
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(0xFFEF7F4D),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'Vanaf de 2 punter lijn',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Bullpen3D',
fontSize: 20,
),
),
height: 100,
width: 100,
));
}
}
class CardDesign6 extends StatefulWidget {
#override
_CardDesign6State createState() => _CardDesign6State();
}
class _CardDesign6State extends State<CardDesign6> {
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
setState(() {
Counter2.counter++;
});
},
child: Container(
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(0xFFEF7F4D),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'Vanaf de 1 punter lijn',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Bullpen3D',
fontSize: 20,
),
),
height: 100,
width: 100,
));
}
}
//#endregion
class HoopDesign extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
height: 100.0,
width: 100.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/basketballhoop.jpg'),
),
shape: BoxShape.circle,
),
);
}
}
//#region Counters integers
class Counter {
static int counter = 0;
}
class Counter2 {
static int counter = 0;
}
//#endregion
Main:
import 'package:flutter/material.dart';
import 'input_page.dart';
void main() => runApp(BasketballCounter());
class BasketballCounter extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Color(0xFFEE682D),
scaffoldBackgroundColor: Color(0xFFEE682D),
),
home: InputPage(),
);
}
}
What the app looks like:
(see the 0 on the side of the top hoop)
https://i.imgur.com/JwLnVaU.png
I appreciate the help :)

You need to re-render InputPage to get the new value of the counter.
Sample: (I refactored the code, refer to HalfCourt widget)
class InputPage extends StatelessWidget {
const InputPage({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('basketball counter'),
),
body: Column(
children: <Widget>[
const Expanded(child: HalfCourt()),
const Expanded(child: HalfCourt(isUpperSide: false)),
],
),
);
}
}
class HalfCourt extends StatefulWidget {
const HalfCourt({
this.isUpperSide = true,
Key? key,
}) : super(key: key);
final bool isUpperSide;
#override
_HalfCourtState createState() => _HalfCourtState();
}
class _HalfCourtState extends State<HalfCourt> {
int counter = 0;
#override
Widget build(BuildContext context) {
final Widget hoopAndScore = Expanded(
child: Row(
children: <Widget>[
const Expanded(child: HoopDesign()),
Text(counter.toString())
],
),
);
return Column(
children: <Widget>[
if (widget.isUpperSide) hoopAndScore,
Row(
children: <Widget>[
Expanded(
child: CardDesign(
onPressed: () => setState(() => counter++),
text: 'Vanaf de 1 punter lijn',
),
),
Expanded(
child: CardDesign(
onPressed: () => setState(() => counter += 3),
text: 'Vanaf de 3 punter lijn!',
),
),
Expanded(
child: CardDesign(
onPressed: () => setState(() => counter += 2),
text: 'Vanaf de 2 punter lijn',
),
),
],
),
if (!widget.isUpperSide) hoopAndScore
],
);
}
}
class CardDesign extends StatelessWidget {
CardDesign({
required this.onPressed,
required this.text,
Key? key,
}) : super(key: key);
final VoidCallback onPressed;
final String text;
#override
Widget build(BuildContext context) {
return InkWell(
onTap: onPressed,
child: Container(
height: 100,
width: 100,
margin: const EdgeInsets.all(15),
decoration: const BoxDecoration(
color: Color(0xFFEF7F4D),
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: 'Bullpen3D',
fontSize: 20,
),
),
),
);
}
}
class HoopDesign extends StatelessWidget {
const HoopDesign({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 100.0,
width: 100.0,
color: Colors.orange,
);
}
}

Related

How can I create a ListView correctly?

I'm not able to create a Listview in Flutter because of when I create a Listview of widgets the screen stays empty, it's something like that 1
This is the Code that I wrote and returns a list view:
import 'package:dietapp/pages/homepage.dart';
import 'package:dietapp/pages/list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dietapp/pages/profile.dart';
import 'package:dietapp/pages/createReg.dart';
import 'package:percent_indicator/percent_indicator.dart';
void main() {}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
const SafeArea(child: TopBar()),
const Align(
alignment: Alignment.topLeft,
child: Padding(
padding: EdgeInsets.only(left: 25, bottom: 20),
child: Text('Seguiment Diari', style: TextStyle(fontSize: 20)),
)),
Align(alignment: Alignment.center, child: TypesListView()),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => const CreateReg()));
},
label: const Text('Crear'),
icon: const Icon(Icons.add),
),
);
}
}
class TopBar extends StatelessWidget {
const TopBar({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(25.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
"Dietapp",
style: TextStyle(
color: Colors.black, fontSize: 30, fontWeight: FontWeight.bold),
),
],
),
);
}
}
class TotalLabel extends StatefulWidget {
final String typeOf;
final String subtitle;
final Function() onPressed;
final double fillBar;
const TotalLabel(
{required this.typeOf,
required this.subtitle,
required this.onPressed,
required this.fillBar,
Key? key})
: super(key: key);
#override
State<TotalLabel> createState() => _TotalLabelState();
}
class _TotalLabelState extends State<TotalLabel> {
Color getColor(double fillBar) {
if (fillBar < 0.5) {
return Colors.orange;
} else {
return Colors.green;
}
}
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onPressed,
child: Container(
width: 350,
height: 125,
padding: const EdgeInsets.all(15.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12.5),
boxShadow: [
BoxShadow(
offset: const Offset(10, 20),
blurRadius: 10,
spreadRadius: 0,
color: Colors.grey.withOpacity(.05)),
],
),
child: Column(
children: [
Text(widget.typeOf,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,
)),
const SizedBox(
height: 5,
),
Text(
widget.subtitle,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.grey,
fontWeight: FontWeight.normal,
fontSize: 12),
),
const SizedBox(
height: 10,
),
const Spacer(),
LinearPercentIndicator(
width: 300,
lineHeight: 10,
barRadius: const Radius.circular(50),
backgroundColor: Colors.black12,
progressColor: getColor(widget.fillBar),
percent: widget.fillBar,
),
const Spacer()
],
),
),
);
}
}
class TypesListView extends StatelessWidget {
const TypesListView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.all(8),
children: <Widget>[
TotalLabel(
typeOf: 'Proteines',
subtitle: 'Range',
onPressed: () {},
fillBar: 0.2),
],
);
}
}
When I run the code, the error view is the following:
I have also tried to use a Stateless widget returning a list view but didn't worked.
Thanks you so much :)
The following is an example of how to use a ListView. Note that I created a MaterialApp since ListView is a Material Widget. You can replace ListViewExample with your own Widget containing a ListView.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ListView Example',
home: ListViewExample(),
);
}
}
class ListViewExample extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.all(8),
children: <Widget>[
Text('Text Widget 1'),
Text('Text Widget 2'),
Text('Text Widget 3'),
],
);
}
}
ListView.builder(
itemCount: 5
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(10),
child: Text("Some text $index")
),
);
}),
More about listview

Tried creating tabs in product detail page in flutter. But tabs is in stateful widget. When I inserted tab class name in home class, getting error

I need to insert tabs below elevated button. When I am using it as separate file, its working fine. Please suggest any ways to insert tabs in this code. I am in the learning stage of flutter.Here is the code link on codepen.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: Home());
}
}
class TabsPart extends StatefulWidget {
#override
_TabsPartState createState() => _TabsPartState();
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome to Flutter'),
),
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
child: Container(
alignment: Alignment.topCenter,
decoration: const BoxDecoration(
image: DecorationImage(
alignment: Alignment.bottomRight,
fit: BoxFit.cover,
image: AssetImage('assets/images/img1.png'))),
),
),
Positioned(
bottom: 0,
child: Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.lightBlue,
borderRadius: BorderRadius.circular(14),
),
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Container(
margin: const EdgeInsets.only(bottom: 16),
width: 12 * 1.5,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(3),
),
),
),
const ProductNameAndPrice(),
const Spacing(),
const ProductDesc(),
const Spacing(),
const SizedBox(
height: 16,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
onSurface: Colors.white),
onPressed: null,
child: Text('Add to Cart',
style: TextStyle(
color: Colors.white, fontSize: 16)),
),
const Spacing(),
],
),
),
))
],
),
),
),
),
);
}
}
class Spacing extends StatelessWidget {
const Spacing({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return const SizedBox(
height: 16,
);
}
}
class RectButton extends StatelessWidget {
final String label;
const RectButton({
Key? key,
required this.label,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 32,
width: 32,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(9),
border: Border.all(color: Colors.white)),
child: Center(
child: Text(
label,
style: TextStyle(color: Colors.white, fontSize: 20),
)),
);
}
}
class ProductNameAndPrice extends StatelessWidget {
const ProductNameAndPrice({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Product 1',
style: TextStyle(
color: Color.fromARGB(255, 250, 235, 235), fontSize: 30),
),
Text(
'\u{20B9}${150}',
style: TextStyle(color: Colors.white, fontSize: 20),
),
],
);
}
}
class ProductDesc extends StatelessWidget {
const ProductDesc({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'This is a good product with \nexcellent quality. purchase it as soon as possible! \nFew numbers only Left in stocks',
style: TextStyle(color: Colors.white, fontSize: 16, height: 1.6)),
],
);
}
}
class _TabsPartState extends State<TabsPart> {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(
icon: Icon(Icons.android),
text: "Tab 1",
),
Tab(icon: Icon(Icons.phone_iphone), text: "Tab 2"),
],
),
title: Text('TutorialKart - TabBar & TabBarView'),
),
body: TabBarView(
children: [
Center(child: Text("Page 1")),
Center(child: Text("Page 2")),
],
),
),
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: Home());
}
}
class Home extends StatefulWidget {
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
late TabController _tabController;
#override
void initState() {
_tabController = TabController(length: 2, vsync: this);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
const ProductNameAndPrice(),
const ProductDesc(),
const SizedBox(height: 16),
ElevatedButton(
style: ElevatedButton.styleFrom(onSurface: Colors.black),
onPressed: null,
child: Text('Add to Cart',
style: TextStyle(color: Colors.black, fontSize: 16)),
),
TabBar(
indicatorColor: Colors.grey,
controller: _tabController,
tabs: [
const Tab(
icon: Icon(
Icons.widgets,
color: Colors.black,
),
),
Tab(
icon: Icon(
Icons.widgets,
color: Colors.black,
),
),
],
),
Expanded(
child: TabBarView(
controller: _tabController,
children: const [
Text("POSTS"),
Text("REELS"),
],
),
),
]),
);
}
}
class RectButton extends StatelessWidget {
final String label;
const RectButton({
Key? key,
required this.label,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 32,
width: 32,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(9),
border: Border.all(color: Colors.white)),
child: Center(
child: Text(
label,
style: TextStyle(color: Colors.white, fontSize: 20),
)),
);
}
}
class ProductNameAndPrice extends StatelessWidget {
const ProductNameAndPrice({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Product 1',
style: TextStyle(color: Colors.black, fontSize: 30),
),
Text(
'\u{20B9}${150}',
style: TextStyle(color: Colors.black, fontSize: 20),
),
],
);
}
}
class ProductDesc extends StatelessWidget {
const ProductDesc({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'This is a good product with \nexcellent quality. purchase it as soon as possible! \nFew numbers only Left in stocks',
style: TextStyle(color: Colors.black, fontSize: 16, height: 1.6)),
],
);
}
}
try this

Flutter nested widgets setState does not work as intended

I have the following structure:
MainBlock. main statefull widget. contains two widgets BlockA and BlockB.
BlockA. contains a text and a button.
BlockB. contains another widget, BlockBCard, which will be used several times (two times in this example).
What works as intended? When I click on the button in BlockA, the content of the text field in BlockA and BlockBCard changers as desired.
Now to my problem:
In BlockB. In order to use setState, I changed BlockB to a StatefulWidget.
Clicking on the button in the BlockBCard, changes the text field in both BlockBCard’s as desired.
But the content of the text field in BlockA does not change.
how can I implement the following:
Click on the button in one of the BlockBCard’s, both the text field in BlockA and the two text fields in BlockBCard change?
Click on the button in one of the BlockBCard’s, the text field in BlockA changes and the text field in the BlockBCard changes but the text field in the second BlockBCard does not change.
Sample Code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
int testCounter = 0;
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MainBlock(),
);
}
}
// ------------------------------------ Stateless Widget <<<
class MainBlock extends StatefulWidget {
#override
_MainBlockState createState() => _MainBlockState();
}
class _MainBlockState extends State<MainBlock> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.all(30.0),
color: Color(0xFF122C39),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: BlockA(
counter: testCounter,
button: () {
setState(() {
testCounter++;
});
},
),
),
Expanded(
child: BlockB(),
),
],
),
),
);
}
}
class BlockA extends StatelessWidget {
final int counter;
final Function button;
BlockA({this.counter, this.button});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10.0),
color: Color(0xFF265672),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: Text(
counter.toString(),
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
Center(
child: GestureDetector(
onTap: button,
child: Text(
'Button',
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
),
],
),
);
}
}
class BlockB extends StatefulWidget {
#override
_BlockBState createState() => _BlockBState();
}
class _BlockBState extends State<BlockB> {
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10.0),
color: Color(0xFF265672),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: BlockBCard(
counter: testCounter,
button: () {
setState(() {
testCounter++;
});
},
),
),
Expanded(
child: BlockBCard(
counter: testCounter,
),
),
],
),
);
}
}
class BlockBCard extends StatelessWidget {
final int counter;
final Function button;
BlockBCard({this.counter, this.button});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(30.0),
color: Color(0xFF4C93C7),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: Text(
counter.toString(),
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
Center(
child: GestureDetector(
onTap: button,
child: Text(
'Button',
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
),
],
),
);
}
}
OK, I have now improved my code so that the button in the BlockBCard's calls a function myBrain that executes a calculation, the result of which is output in BlockA.
Now I would like to increase the text field in the BlockBCard's by 1, but only in the respective card in which the button is pressed and not in all cards. With my current code, all cards are incorrectly increased by 1.
In this example there are only two cards, but in the implementation there will be multiple cards.
Here is my current code. to simplify the example, I removed BlockB and placed the BlockBCard's directly into the MainBlock:
How can I increase the text field in the BlockBCard's by 1, but only in the respective card in which the button is pressed and not in all cards?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MainBlock(),
);
}
}
// OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO MainBlock >>>
class MainBlock extends StatefulWidget {
#override
_MainBlockState createState() => _MainBlockState();
}
class _MainBlockState extends State<MainBlock> {
int totalCounter = 0;
int singleCounter = 0;
void myBrain() {
totalCounter = totalCounter + 5;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.all(30.0),
color: Color(0xFF122C39),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: BlockA(
counter: totalCounter,
button: () {
setState(() {
totalCounter = 0;
});
},
),
),
Expanded(
child: BlockBCard(
counter: singleCounter,
button: () {
setState(() {
myBrain();
singleCounter++;
});
},
),
),
Expanded(
child: BlockBCard(
counter: singleCounter,
button: () {
setState(() {
myBrain();
singleCounter++;
});
},
),
),
],
),
),
);
}
}
// OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO MainBlock <<<
// OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO BlockA >>>
class BlockA extends StatelessWidget {
final int counter;
final Function button;
BlockA({this.counter, this.button});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10.0),
color: Color(0xFF265672),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: Text(
counter.toString(),
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
Center(
child: GestureDetector(
onTap: button,
child: Text(
'Button',
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
),
],
),
);
}
}
// OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO BlockA <<<
// OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO BlockBCard >>>
class BlockBCard extends StatelessWidget {
final int counter;
final Function button;
BlockBCard({this.counter, this.button});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(30.0),
color: Color(0xFF4C93C7),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: Text(
counter.toString(),
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
Center(
child: GestureDetector(
onTap: button,
child: Text(
'Button',
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
),
],
),
);
}
}
// OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO BlockBCard <<<
You got the issue because when you change the value of blockB it could not rebuild ta blockA but it change the global value if you will want to change the blockA's from blockB you should pass as like blockA.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
int testCounter = 0;
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MainBlock(),
);
}
}
// ------------------------------------ Stateless Widget <<<
class MainBlock extends StatefulWidget {
#override
_MainBlockState createState() => _MainBlockState();
}
class _MainBlockState extends State<MainBlock> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.all(30.0),
color: Color(0xFF122C39),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: BlockA(
counter: testCounter,
button: () {
setState(() {
testCounter++;
});
},
),
),
Expanded(
child: BlockB(
counter: testCounter,
button: () {
setState(() {
testCounter++;
});
}),
),
],
),
),
);
}
}
class BlockA extends StatelessWidget {
final int counter;
final Function button;
BlockA({this.counter, this.button});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10.0),
color: Color(0xFF265672),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: Text(
counter.toString(),
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
Center(
child: GestureDetector(
onTap: button,
child: Text(
'Button',
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
),
],
),
);
}
}
class BlockB extends StatefulWidget {
final int counter;
final Function button;
BlockB({this.counter, this.button});
#override
_BlockBState createState() => _BlockBState();
}
class _BlockBState extends State<BlockB> {
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10.0),
color: Color(0xFF265672),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: BlockBCard(
counter: testCounter,
button:widget.button,
),
),
Expanded(
child: BlockBCard(
counter: testCounter,
),
),
],
),
);
}
}
class BlockBCard extends StatelessWidget {
final int counter;
final Function button;
BlockBCard({this.counter, this.button});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(30.0),
color: Color(0xFF4C93C7),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: Text(
counter.toString(),
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
Center(
child: GestureDetector(
onTap: button,
child: Text(
'Button',
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
),
],
),
);
}
}
As #Jahidul Islam explained, you have to pass your data from MainBlock to BlocB as you do from MainBlock to BlocA.
In general in Flutter, you want to avoid using mutable global variable precisely for that reason. When a variable update, flutter does not know about it. If you call setState the widget tree bellow will be rebuild.
This is why you will often hear "Lift the state up" because the state has to be contained in a high enough widget so that it can be passed down through the widget tree to every widget that needs it. In your case, since BlocA and BlockBCard need the counter, it has to be created inside there lower common ancestor: MainBlock.
Here is the concrete implementation but the most important thing is to have understood the reasoning explained above:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MainBlock(),
);
}
}
class MainBlock extends StatefulWidget {
#override
_MainBlockState createState() => _MainBlockState();
}
class _MainBlockState extends State<MainBlock> {
int testCounter = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.all(30.0),
color: Color(0xFF122C39),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: BlockA(
counter: testCounter,
button: () {
setState(() {
testCounter++;
});
},
),
),
Expanded(
child: BlockB(
counter: testCounter,
button: () {
setState(() {
testCounter++;
});
},
),
),
],
),
),
);
}
}
class BlockA extends StatelessWidget {
final int counter;
final VoidCallback button;
BlockA({required this.counter, required this.button});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10.0),
color: Color(0xFF265672),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: Text(
counter.toString(),
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
Center(
child: GestureDetector(
onTap: button,
child: Text(
'Button',
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
),
],
),
);
}
}
class BlockB extends StatelessWidget {
final int counter;
final VoidCallback button;
BlockB({required this.counter, required this.button});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10.0),
color: Color(0xFF265672),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: BlockBCard(
counter: counter,
button: button,
),
),
Expanded(
child: BlockBCard(
counter: counter,
),
),
],
),
);
}
}
class BlockBCard extends StatelessWidget {
final int counter;
final VoidCallback? button;
BlockBCard({required this.counter, this.button});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(30.0),
color: Color(0xFF4C93C7),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: Text(
counter.toString(),
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
Center(
child: GestureDetector(
onTap: button ?? (() {}),
child: Text(
'Button',
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 22.0,
),
),
),
),
],
),
);
}
}
If we refresh the MainBlock it's children will also get the updated state. We can use callback for it.
On BlocKB
class BlockB extends StatefulWidget {
final VoidCallback ontap;
const BlockB({
Key? key,
required this.ontap,
}) : super(key: key);
#override
_BlockBState createState() => _BlockBState();
}
class _BlockBState extends State<BlockB> {
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10.0),
color: Color(0xFF265672),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: BlockBCard(
counter: testCounter,
button: () {
// setState(() { /// we dont need it while parent widget will refress it
testCounter++;
// });
widget.ontap();
},
),
),
Expanded(
child: BlockBCard(
counter: testCounter,
button: () {
/// you may also wanted to increment here
testCounter++;
widget.ontap();
},
),
),
],
),
);
}
}
On MainBlock
Expanded(
child: BlockB(
ontap: () {
setState(() {});
},
),
),

Flutter - Chat Screen built with a StreamBuilder showing messages multiple times

I am struggling with this Chat Screen. The app is meant to ask questions (not part of the below code) and the user either selects answers or types them. When the user types a first answer everything goes according to the plan and a first message is displayed. However the app then goes on displaying the second answer twice, the third one three times and so on.
I have been facing this issue for a few days and I cannot figure out why the app behaves the way it does. Could you please take a look at the code and suggest a way to fix this?
To give you some background information, this Chat Screen is part of a larger application. It should subscribe to a stream when the user opens the app. Then each message is pushed to the stream, whether it is a question asked by the bot or an answer given by the User. The system listens to the stream and displays a new message each time the stream broadcasts something, in our case the latest user input.
I am using a list of message models built from the stream to display the messages. For the purpose of asking this question I simplified the model to the extreme but in practice it has 23 fields. Creating this list of messages is the best solution I managed to think of but there may be a better way to handle this situation. Feel free to let me know if you know of any.
Here is the code that I am running.
import 'package:flutter/material.dart';
import 'dart:async';
StreamController<ChatMessageModel> _chatMessagesStreamController = StreamController<ChatMessageModel>.broadcast();
Stream _chatMessagesStream = _chatMessagesStreamController.stream;
const Color primaryColor = Color(0xff6DA7B9);
const Color secondaryColor = Color(0xffF0F0F0);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Chat Screen',
home: ChatScreen(),
);
}
}
class ChatMessageModel {
final String message;
const ChatMessageModel({
this.message,
}
);
factory ChatMessageModel.turnSnapshotIntoListRecord(Map data) {
return ChatMessageModel(
message: data['message'],
);
}
#override
List<Object> get props => [
message,
];
}
class ChatScreen extends StatefulWidget {
static const String id = 'chat_screen9';
#override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final _messageTextController = TextEditingController();
String _userInput;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: secondaryColor,
appBar: AppBar(
title: Row(
children: [
Container(
padding: EdgeInsets.all(8.0),
child: Text('Chat Screen',
style: TextStyle(color: Colors.white,),
),
)
],
),
backgroundColor: primaryColor,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
MessagesStream(),
Container(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: primaryColor,
width: 1.0,
),
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
controller: _messageTextController,
onChanged: (value) {
_userInput = value;
},
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
hintText: 'Type your answer here',
// border: InputBorder.none,
),
),
),
TextButton(
onPressed: () {
_messageTextController.clear();
debugPrint('Adding a ChatMessageModel with the message $_userInput to the Stream');
ChatMessageModel chatMessageModelRecord = ChatMessageModel(message: _userInput);
_chatMessagesStreamController.add(chatMessageModelRecord,);
},
child: Text(
'OK',
style: TextStyle(
color: primaryColor,
fontWeight: FontWeight.bold,
fontSize: 18.0,
),
),
),
],
),
),
],
),
),
);
}
}
class MessagesStream extends StatelessWidget {
List<ChatMessageModel> _allMessagesContainedInTheStream = [];
#override
Widget build(BuildContext context) {
return StreamBuilder<ChatMessageModel>(
stream: _chatMessagesStream,
builder: (context, snapshot) {
_chatMessagesStream.listen((streamedMessages) {
// _allMessagesContainedInTheStream.clear();
debugPrint('Value from controller: $streamedMessages');
_allMessagesContainedInTheStream.add(streamedMessages);
}
);
return Expanded(
child: ListView.builder(
// reverse: true,
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
itemCount: _allMessagesContainedInTheStream.length,
itemBuilder: (BuildContext context, int index) {
if (snapshot.hasData) {
return UserChatBubble(chatMessageModelRecord: _allMessagesContainedInTheStream[index]);
}
},
),
);
},
);
}
}
class UserChatBubble extends StatelessWidget {
final ChatMessageModel chatMessageModelRecord;
const UserChatBubble({
Key key,
#required this.chatMessageModelRecord,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: EdgeInsets.symmetric(vertical: 5, horizontal: 5,),
child: Container(
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 7 / 10,),
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(15.0),
bottomRight: Radius.circular(15.0),
topLeft: Radius.circular(15.0),
),
color: primaryColor,
),
padding: EdgeInsets.symmetric(vertical: 8, horizontal: 20,),
child: Text(chatMessageModelRecord.message,
style: TextStyle(
fontSize: 17,
// fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
],
);
}
}
First of all, thank you for the interesting problem and functioning example provided. I had to do some small changes to convert it to "null-safety", but my code should work on your computer too.
The only problem you had initialization of _chatMessagesStream listener. You should do it only once and ideally in initState, to call it only once.
So here is the fix for you:
class MessagesStream extends StatefulWidget {
#override
_MessagesStreamState createState() => _MessagesStreamState();
}
class _MessagesStreamState extends State<MessagesStream> {
final List<ChatMessageModel> _allMessagesContainedInTheStream = [];
#override
void initState() {
_chatMessagesStream.listen((streamedMessages) {
// _allMessagesContainedInTheStream.clear();
debugPrint('Value from controller: $streamedMessages');
_allMessagesContainedInTheStream.add(streamedMessages);
});
super.initState();
}
#override
Widget build(BuildContext context) {
return StreamBuilder<ChatMessageModel>(
stream: _chatMessagesStream,
builder: (context, snapshot) {
return Expanded(
child: ListView.builder(
// reverse: true,
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
itemCount: _allMessagesContainedInTheStream.length,
itemBuilder: (BuildContext context, int index) {
if (snapshot.hasData) {
return UserChatBubble(
chatMessageModelRecord:
_allMessagesContainedInTheStream[index],
);
} else {
print(snapshot.connectionState);
return Container();
}
},
),
);
},
);
}
}
Also providing full code for null-safety just in case!
import 'package:flutter/material.dart';
import 'dart:async';
final StreamController<ChatMessageModel> _chatMessagesStreamController =
StreamController<ChatMessageModel>.broadcast();
final Stream<ChatMessageModel> _chatMessagesStream =
_chatMessagesStreamController.stream;
const Color primaryColor = Color(0xff6DA7B9);
const Color secondaryColor = Color(0xffF0F0F0);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Chat Screen',
home: ChatScreen(),
);
}
}
class ChatMessageModel {
final String? message;
const ChatMessageModel({
this.message,
});
factory ChatMessageModel.turnSnapshotIntoListRecord(Map data) {
return ChatMessageModel(
message: data['message'],
);
}
List<Object> get props => [
message!,
];
}
class ChatScreen extends StatefulWidget {
static const String id = 'chat_screen9';
#override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final _messageTextController = TextEditingController();
String? _userInput;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: secondaryColor,
appBar: AppBar(
title: Row(
children: [
Container(
padding: EdgeInsets.all(8.0),
child: Text(
'Chat Screen',
style: TextStyle(
color: Colors.white,
),
),
)
],
),
backgroundColor: primaryColor,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
MessagesStream(),
Container(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: primaryColor,
width: 1.0,
),
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
controller: _messageTextController,
onChanged: (value) {
_userInput = value;
},
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 20.0),
hintText: 'Type your answer here',
// border: InputBorder.none,
),
),
),
TextButton(
onPressed: () {
_messageTextController.clear();
debugPrint(
'Adding a ChatMessageModel with the message $_userInput to the Stream');
ChatMessageModel chatMessageModelRecord =
ChatMessageModel(message: _userInput);
_chatMessagesStreamController.add(
chatMessageModelRecord,
);
},
child: Text(
'OK',
style: TextStyle(
color: primaryColor,
fontWeight: FontWeight.bold,
fontSize: 18.0,
),
),
),
],
),
),
],
),
),
);
}
}
class MessagesStream extends StatefulWidget {
#override
_MessagesStreamState createState() => _MessagesStreamState();
}
class _MessagesStreamState extends State<MessagesStream> {
final List<ChatMessageModel> _allMessagesContainedInTheStream = [];
#override
void initState() {
_chatMessagesStream.listen((streamedMessages) {
// _allMessagesContainedInTheStream.clear();
debugPrint('Value from controller: $streamedMessages');
_allMessagesContainedInTheStream.add(streamedMessages);
});
super.initState();
}
#override
Widget build(BuildContext context) {
return StreamBuilder<ChatMessageModel>(
stream: _chatMessagesStream,
builder: (context, snapshot) {
return Expanded(
child: ListView.builder(
// reverse: true,
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
itemCount: _allMessagesContainedInTheStream.length,
itemBuilder: (BuildContext context, int index) {
if (snapshot.hasData) {
return UserChatBubble(
chatMessageModelRecord:
_allMessagesContainedInTheStream[index],
);
} else {
print(snapshot.connectionState);
return Container();
}
},
),
);
},
);
}
}
class UserChatBubble extends StatelessWidget {
final ChatMessageModel chatMessageModelRecord;
const UserChatBubble({
Key? key,
required this.chatMessageModelRecord,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: EdgeInsets.symmetric(
vertical: 5,
horizontal: 5,
),
child: Container(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 7 / 10,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(15.0),
bottomRight: Radius.circular(15.0),
topLeft: Radius.circular(15.0),
),
color: primaryColor,
),
padding: EdgeInsets.symmetric(
vertical: 8,
horizontal: 20,
),
child: Text(
"${chatMessageModelRecord.message}",
style: TextStyle(
fontSize: 17,
// fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
],
);
}
}

How to clear Flutter Text Field from parent widget

How to clear Flutter Text Field from parent widget
I am a newbie for flutter and dart. I am developing a calculator type application.
I want to clear the text field in the TextFieldContainer1 class from my parent widget Calculator method using method function.
This is the parent widget (Calculator) which contains reset function.
class Calculator extends StatefulWidget {
#override
_CalculatorState createState() => _CalculatorState();
}
class _CalculatorState extends State<Calculator> {
double soldPrice=0.00;
reset(){
soldPrice=0.00;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: BgColor ,
bottomNavigationBar: Container(
decoration: BoxDecoration(
borderRadius:BorderRadius.only(topLeft: Radius.circular(10), topRight:Radius.circular(10) ),
color:YellowBg,
),
alignment: Alignment.center,
height: 50,
child: Text('RESET',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
letterSpacing: 5,
),
),
),
body: SafeArea(
child: Column(
children: <Widget>[
SizedBox(height:10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
EcalLogo(logoSize: 30,),
],
),
SizedBox(height:10),
Padding(
padding:EdgeInsets.symmetric(horizontal:10.0),
child:FractionallySizedBox(
widthFactor: 0.9,
child: Container(
height:1.0,
width:130.0,
color:Colors.white,),
),),
SizedBox(height: 10,),
Expanded(
child:ListView(
children: <Widget>[
TextFieldContainer1(
title: 'SOLD PRICE',
tagLine: "SALE PRICE WITOHUT SHIPPING",
icon: Icons.check_circle,
onChange: (val) => setState(() {
soldPrice = double.parse(val);
})
),
],
))
],
),
)
);
}
}
This is the child widget class(TextFieldContainer1)
class TextFieldContainer1 extends StatefulWidget {
final String title;
final String tagLine;
final IconData icon;
final Function(String) onChange;
// Function displayFunction;
TextFieldContainer1({this.title,this.tagLine,this.icon,this.onChange});
#override
_TextFieldContainer1State createState() => _TextFieldContainer1State();
}
class _TextFieldContainer1State extends State<TextFieldContainer1> {
#override
Widget build(BuildContext context) {
return FractionallySizedBox(
widthFactor: 0.95,
child: Container(
padding: EdgeInsets.symmetric(horizontal:20, vertical:5),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)),
color: tileBackground,
),
height: 57,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:<Widget>[
Container(
child:Column(
children:<Widget>[
Row(
children:<Widget>[
Icon(widget.icon,
color:Color.fromRGBO(255, 255, 255, 0.7),
size:20
),
SizedBox(width:15),
Text(widget.title,
style: TextStyle(
fontSize: 20,
color:Colors.white,
fontWeight: FontWeight.w500
),
)
]
),
Text(widget.tagLine,
style: TextStyle(
color:Color.fromRGBO(255, 255, 255, 0.5),
fontSize: 12
),
)
]
)
),
Container(
padding: EdgeInsets.symmetric(horizontal: 15,vertical: 5),
decoration: BoxDecoration(
color: Color.fromRGBO(252, 205, 0, 0.2),
borderRadius: BorderRadius.all(Radius.circular(10)
)
),
height: 40,
width: 92,
child: TextField(
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20
),
autofocus: false,
decoration:InputDecoration(
focusColor: YellowBg,
fillColor: YellowBg,
hoverColor: YellowBg,
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: YellowBg),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: YellowBg),)
) ,
keyboardType: TextInputType.number,
onChanged: widget.onChange,
),
)
],
),
),
);
}
}
How to clear the text field in the TextFieldContainer1 class from my parent widget Calculator using the reset function?
make your text field accept a controller:
class TextFieldContainer1 extends StatefulWidget {
final String title;
final String tagLine;
final IconData icon;
final Function(String) onChange;
final TextEditingController controller;
// Function displayFunction;
TextFieldContainer1({this.title,this.tagLine,this.icon,this.onChange,
this.controller});
#override
_TextFieldContainer1State createState() => _TextFieldContainer1State();
}
class _TextFieldContainer1State extends State<TextFieldContainer1> {
// also don't forget to dispose the controller
#override
void dispose() {
super.dispose();
_controller.dispose();
}
}
and use it in your widget like this:
class Calculator extends StatefulWidget {
#override
_CalculatorState createState() => _CalculatorState();
}
class _CalculatorState extends State<Calculator> {
final _controller = TextEditingController();
double soldPrice=0.00;
reset(){
soldPrice=0.00;
}
#override
Widget build(BuildContext context) {
// ....
TextFieldContainer1(
title: 'SOLD PRICE',
tagLine: "SALE PRICE WITOHUT SHIPPING",
icon: Icons.check_circle,
controller: _controller,
onChange: (val) => setState(() {
soldPrice = double.parse(val);
}),
),
],
))
void reset() => _controller.clear();
// ....