How to Render data from Request inside a FutureBuilder - dart

I'm trying to list pokemons from my api, its works when i call the list but when i try to get the data for each pokemon it doesn't render the data.
updated the code for the #Gazihan Alankus answer.
Widget build(BuildContext context) {
return FutureBuilder<PokeData>(
future: api.getPokemonList(),
builder: (
BuildContext context,
AsyncSnapshot<PokeData> pokedata
) {
if(pokedata.hasData && pokedata.connectionState == ConnectionState.done) {
return Container(
child: ListView(
children: pokedata.data.results.map((pokemon) {
FutureBuilder(
future: api.getPokeDetail(pokemon.url),
builder: (
BuildContext context,
AsyncSnapshot snapshot
) {
print('------------widget------------');
if(snapshot.hasData && snapshot.connectionState == ConnectionState.done) {
return Container(child: PokemonWidget(
pokemon.name,
snapshot.data.sprites.normal,
snapshot.data.types
),);
} else {
return Container(
child: CircularProgressIndicator(),
);
}
}
);
}).toList(),
),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}
But now i am getting this error when the app is running, the first request works well but it never call the second request.
flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during performLayout():
flutter: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 553 pos 12: 'child != null': is
flutter: not true.
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter: https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: (elided 5 frames from class _AssertionError and package dart:async)
flutter:
flutter: The following RenderObject was being processed when the exception was fired:
flutter: RenderSliverList#04cee relayoutBoundary=up2 NEEDS-LAYOUT NEEDS-PAINT
flutter: creator: SliverList ← MediaQuery ← SliverPadding ← Viewport ← IgnorePointer-[GlobalKey#b48da] ←
flutter: Semantics ← Listener ← _GestureSemantics ←
flutter: RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#865eb] ← _ScrollableScope ←
flutter: _ScrollSemantics-[GlobalKey#8f9cb] ← Scrollable ← ⋯
flutter: parentData: paintOffset=Offset(0.0, 0.0) (can use size)
flutter: constraints: SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle,
flutter: scrollOffset: 0.0, remainingPaintExtent: 603.0, crossAxisExtent: 375.0, crossAxisDirection:
flutter: AxisDirection.right, viewportMainAxisExtent: 667.0, remainingCacheExtent: 853.0 cacheOrigin: 0.0 )
flutter: geometry: null
flutter: no children current live
flutter: This RenderObject has no descendants.
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: Another exception was thrown: NoSuchMethodError: The getter 'scrollOffsetCorrection' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method 'debugAssertIsValid' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The getter 'visible' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The getter 'visible' was called on null.

One way is to create a FutureBuilder per item, like so:
Widget build(BuildContext context) {
return FutureBuilder<PokeData>(
future: api.getPokemonList(),
builder: (
BuildContext context,
AsyncSnapshot<PokeData> snapshot
) {
if(snapshot.hasData && snapshot.connectionState == ConnectionState.done) {
return Container(
child: ListView(
children: snapshot.data.results.map((pokemon) {
FutureBuilder(
future: api.getPokeDetail(pokemon.url),
builder: (
BuildContext context,
AsyncSnapshot snapshot
) {
if(snapshot.hasData && snapshot.connectionState == ConnectionState.done) {
return PokemonWidget(
pokemon.name,
resp.sprites.normal,
resp.types
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}
)
}).toList(),
),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}

Related

TabBarView in TabBar to take up the remaining space

I have been using TabBar() in my flutter app, and it was working unless I found it my TabBarView() messes up when the screen size changes.
After following this question I have found out the solution to my problem is Expanded() for TabBarView(). I have tried my level best but all I'm getting is a lot of error regarding rendering my data.
⡿flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during performLayout():
flutter: RenderFlex children have non-zero flex but incoming height constraints are unbounded.
⣟flutter: When a column is in a parent that does not provide a finite height constraint, for example if it is
flutter: in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
flutter: flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
flutter: space in the vertical direction.
flutter: These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
flutter: cannot simultaneously expand to fit its parent.
flutter: Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
flutter: children (using Flexible rather than Expanded). This will allow the flexible children to size
flutter: themselves to less than the infinite remaining space they would otherwise be forced to take, and
flutter: then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
flutter: constraints provided by the parent.
flutter: If this message did not help you determine the problem, consider using debugDumpRenderTree():
flutter: https://flutter.dev/debugging/#rendering-layer
flutter: http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
flutter: The affected RenderFlex is:
flutter: RenderFlex#bc077 relayoutBoundary=up2 NEEDS-LAYOUT NEEDS-PAINT(creator: Column ← TabWidget ← Column ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ← CustomMultiChildLayout ← AnimatedBuilder ← DefaultTextStyle ← AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#4f100 ink renderer] ← NotificationListener<LayoutChangedNotification> ← PhysicalModel ← ⋯, parentData: offset=Offset(0.0, 0.0); flex=null; fit=null (can use size), constraints: BoxConstraints(w=375.0, 0.0<=h<=Infinity), size: MISSING, direction: vertical, mainAxisAlignment: start, mainAxisSize: min, crossAxisAlignment: start, textDirection: ltr, verticalDirection: down)
flutter: The creator information is set to:
flutter: Column ← TabWidget ← Column ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ←
flutter: CustomMultiChildLayout ← AnimatedBuilder ← DefaultTextStyle ← AnimatedDefaultTextStyle ←
flutter: _InkFeatures-[GlobalKey#4f100 ink renderer] ← NotificationListener<LayoutChangedNotification> ←
flutter: PhysicalModel ← ⋯
flutter: The nearest ancestor providing an unbounded width constraint is: RenderFlex#0807f relayoutBoundary=up1 NEEDS-LAYOUT NEEDS-PAINT:
flutter: creator: Column ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ← CustomMultiChildLayout ←
flutter: AnimatedBuilder ← DefaultTextStyle ← AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#4f100 ink
flutter: renderer] ← NotificationListener<LayoutChangedNotification> ← PhysicalModel ←
flutter: AnimatedPhysicalModel ← Material ← ⋯
flutter: parentData: offset=Offset(0.0, 0.0); id=_ScaffoldSlot.body (can use size)
flutter: constraints: BoxConstraints(0.0<=w<=375.0, 0.0<=h<=591.0)
flutter: size: MISSING
flutter: direction: vertical
flutter: mainAxisAlignment: start
flutter: mainAxisSize: min
flutter: crossAxisAlignment: stretch
flutter: verticalDirection: down
flutter: See also: https://flutter.dev/layout/
flutter: If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
flutter: https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 RenderFlex.performLayout.<anonymous closure> (package:flutter/src/rendering/flex.dart:691:11)
flutter: #1 RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:717:10)
flutter: #2 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #3 RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:743:15)
flutter: #4 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #5 MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:142:11)
flutter: #6 _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:443:7)
flutter: #7 MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:212:7)
flutter: #8 RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:356:14)
flutter: #9 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #10 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #11 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #12 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #13 _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1214:11)
flutter: #14 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #15 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #16 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #17 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #18 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #19 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #20 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #21 RenderStack.performLayout (package:flutter/src/rendering/stack.dart:510:15)
flutter: #22 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #23 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #24 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #25 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #26 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #27 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #28 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #29 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #30 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #31 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #32 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #33 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #34 RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:3067:13)
flutter: #35 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #36 RenderStack.performLayout (package:flutter/src/rendering/stack.dart:510:15)
flutter: #37 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #38 __RenderTheatre&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #39 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #40 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #41 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #42 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #43 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #44 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #45 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #46 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #47 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #48 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
flutter: #49 RenderObject.layout (package:flutter/src/rendering/object.dart:1620:7)
flutter: #50 RenderView.performLayout (package:flutter/src/rendering/view.dart:151:13)
flutter: #51 RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1497:7)
flutter: #52 PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:766:18)
flutter: #53 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:346:19)
flutter: #54 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:701:13)
flutter: #55 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:285:5)
flutter: #56 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1012:15)
flutter: #57 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:952:9)
flutter: #58 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:773:7)
flutter: #60 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:382:19)
flutter: #61 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:416:5)
flutter: #62 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
flutter: (elided one frame from package dart:async-patch)
flutter:
flutter: The following RenderObject was being processed when the exception was fired: RenderFlex#bc077 relayoutBoundary=up2 NEEDS-LAYOUT NEEDS-PAINT:
flutter: creator: Column ← TabWidget ← Column ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ←
flutter: CustomMultiChildLayout ← AnimatedBuilder ← DefaultTextStyle ← AnimatedDefaultTextStyle ←
flutter: _InkFeatures-[GlobalKey#4f100 ink renderer] ← NotificationListener<LayoutChangedNotification> ←
flutter: PhysicalModel ← ⋯
⣯flutter: parentData: offset=Offset(0.0, 0.0); flex=null; fit=null (can use size)
flutter: constraints: BoxConstraints(w=375.0, 0.0<=h<=Infinity)
flutter: size: MISSING
flutter: direction: vertical
flutter: mainAxisAlignment: start
flutter: mainAxisSize: min
flutter: crossAxisAlignment: start
flutter: textDirection: ltr
flutter: verticalDirection: down
flutter: This This RenderObject had the following descendants (showing up to depth 5):
flutter: child 1: RenderPadding#ec776 relayoutBoundary=up3 NEEDS-PAINT
flutter: child: RenderDecoratedBox#82c7d relayoutBoundary=up4 NEEDS-PAINT
flutter: child: RenderPadding#47def relayoutBoundary=up5 NEEDS-PAINT
flutter: child: RenderCustomPaint#d3174 relayoutBoundary=up6 NEEDS-PAINT
flutter: child: _TabLabelBarRenderer#1dbbb relayoutBoundary=up7 NEEDS-PAINT
flutter: child 2: _RenderScrollSemantics#ab273 NEEDS-LAYOUT NEEDS-PAINT
flutter: child: RenderPointerListener#85f41 NEEDS-LAYOUT NEEDS-PAINT
flutter: child: RenderSemanticsGestureHandler#dfb17 NEEDS-LAYOUT NEEDS-PAINT
flutter: child: RenderPointerListener#36472 NEEDS-LAYOUT NEEDS-PAINT
flutter: child: RenderSemanticsAnnotations#0d0f0 NEEDS-LAYOUT NEEDS-PAINT
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: Another exception was thrown: RenderBox was not laid out: RenderFlex#bc077 relayoutBoundary=up2 NEEDS-PAINT
flutter: Another exception was thrown: RenderBox was not laid out: RenderFlex#0807f relayoutBoundary=up1 NEEDS-PAINT
flutter: Another exception was thrown: NoSuchMethodError: The method '>' was called on null.
Now to give you an insight of what I have been doing is that, I have a widget class in which I have defined my TabBar and I'm using this in different places.
This is my widget for TabBar class:
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsets.only(left: 16.0, right: 16.0),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.0),
border: Border(bottom: BorderSide(color: Colors.grey, width: 0.5))),
child: TabBar(
unselectedLabelColor: Colors.grey,
unselectedLabelStyle: TextStyle().copyWith(fontSize: 16.0, fontWeight: FontWeight.normal),
labelColor: Color.fromRGBO(253, 92, 99, 1),
labelStyle: TextStyle().copyWith(fontSize: 16.0, fontWeight: FontWeight.bold),
indicatorColor: Color.fromRGBO(253, 92, 99, 1),
indicatorWeight: widget.indicatorWeight,
controller: _controller,
tabs: [
new Tab(
child: Padding(
padding: EdgeInsets.only(top: 18.0),
child: Text(widget.childOneHeader, style: TextStyle(fontSize: 15.0)),
)
),
new Tab(
child: Padding(
padding: EdgeInsets.only(top: 18.0),
child: Text(widget.childTwoHeader, style: TextStyle(fontSize: 15.0)),
)
),
new Tab(
child: Padding(
padding: EdgeInsets.only(top: 18.0),
child: Text(widget.childThreeHeader, style: TextStyle(fontSize: 15.0)),
)
)
]
)
),
Expanded(
//height: widget.layoutHeight,
child: new TabBarView(
controller: _controller,
children: <Widget>[
widget.childOne,
widget.childTwo,
widget.childThree
],
)
)
]
);
The data with widget. is coming from it's constructor.
Now I have been using this in my page which has ListView() for my TabBarView() children, so I'm passing it from them only.
Class Using TabBar Code:
body: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('Heading'),
Container(),
TabWidget(
indicatorWeight: 1.0,
childOneHeader: 'Title 1',
childTwoHeader: 'Title 2',
childThreeHeader: 'Title 3',
childOne: ListView(
shrinkWrap: true,
scrollDirection: Axis.vertical,
children: this.isDataNull ?
[Container(
child: errorWidget,
)]
: this.getOffersWidgets()
),
childTwo: ListView(
shrinkWrap: true,
scrollDirection: Axis.vertical,
children: this.isDataNull ?
[Container(
child: errorWidget,
)]
: this.getBarWidgets()
),
childThree: ListView(
shrinkWrap: true,
scrollDirection: Axis.vertical,
children: this.isDataNull ?
[Container(
child: errorWidget,
)]
: this.getEventWidget()
)
)
]
);
I have tried my level best couldn't get it to work. All I'm getting is a blank page nothing else. Please help me with this. Thanks :)
SOLUTION:
Since I have found a way out, so I think my friends who will see this question in the future will get benefited from the question as well.
This is the link to the answer by the way if you want to take a peek of that : Solution to my problem
In the class using tabbarcode, wrap the TabWidget inside Expanded() and rest will be the same, and your job is done.
body: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('Heading'),
Container(),
Expanded(
child: TabWidget(//your content goes here)
)
Special thanks to MFARKAN.
Please note, never ever uses Expanded() or Flexible() inside the ListView() or any scrollable widget, cos they require a finite height. use it inside the content but not for Expanded()
Thanks Guys! :)
Reiterating the solution to close the thread. As mentioned in this issue ticket posted on GitHub, TabBarView requires a finite height to be rendered. This can be achieved by using Expanded widget as suggested in the error logs posted and on the solution posted in this GitHub thread
Here's a minimal repro that you can try out
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
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> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Expanded(
child: TabWidget(),
),
);
}
}
class TabWidget extends StatefulWidget {
#override
_TabWidgetState createState() => _TabWidgetState();
}
class _TabWidgetState extends State<TabWidget>
with SingleTickerProviderStateMixin {
TabController _controller;
#override
void initState() {
super.initState();
_controller = TabController(length: 3, vsync: this);
}
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Column(
children: <Widget>[
TabBar(
labelColor: Colors.black,
indicatorColor: Colors.blue,
controller: _controller,
tabs: <Widget>[
Tab(
text: 'Tab 1',
),
Tab(
text: 'Tab 2',
),
Tab(
text: 'Tab 3',
),
],
),
Expanded(
child: TabBarView(
controller: _controller,
children: <Widget>[
Center(
child: Text('Tab View 1'),
),
Center(
child: Text('Tab View 2'),
),
Center(
child: Text('Tab View 3'),
),
],
),
)
],
),
);
}
}
How the app looks

Computer Vision with ML Kit - Flutter In Focus

I'm trying to follow the Computer Vision with ML Kit - Flutter In Focus tutorial, where I followed the tutorial step-by step, and still didn't manage to make it work.
my code is as follow:
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:async';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_ml_vision/firebase_ml_vision.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FacePage(),
);
}
}
class FacePage extends StatefulWidget{
#override
createState() => _FacePageState();
}
class _FacePageState extends State<FacePage>{
File _imageFile;
List<Face> _faces;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Face Detector'),
),
body: ImageAndFaces(),
floatingActionButton: FloatingActionButton(
onPressed: _getImageAndDetectFace,
tooltip: 'Pick an Image',
child: Icon(Icons.add_a_photo),
),
);
}
void _getImageAndDetectFace() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.gallery,
);
final image = FirebaseVisionImage.fromFile(imageFile);
final faceDetector = FirebaseVision.instance.faceDetector(
FaceDetectorOptions(
mode: FaceDetectorMode.accurate,
enableLandmarks: true,
),
);
List<Face> faces = await faceDetector.detectInImage(image);
if(mounted) {
setState(() {
_imageFile = imageFile;
_faces = faces;
});
}
}
}
class ImageAndFaces extends StatelessWidget {
ImageAndFaces({this.imageFile, this.faces});
final File imageFile;
final List<Face> faces;
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Flexible(
flex: 2 ,
child: Container(
constraints: BoxConstraints.expand(),
child: Image.file(imageFile, fit: BoxFit.cover),
),
),
Flexible(flex: 1 ,
child: ListView(
children: faces.map<Widget>((f) => FaceCoordinates(f)).toList(),
),
),
],
);
}
}
class FaceCoordinates extends StatelessWidget {
FaceCoordinates(this.face);
final Face face;
#override
Widget build(BuildContext context) {
final pos = face.boundingBox;
return ListTile(
title: Text('(${pos.top}, ${pos.left}, ${pos.bottom}, ${pos.right})'),
);
}
}
I'm getting the following exception stack:
I/flutter ( 5077): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 5077): The following assertion was thrown building ImageAndFaces(dirty):
I/flutter ( 5077): 'package:flutter/src/painting/image_provider.dart': Failed assertion: line 532 pos 14: 'file !=
I/flutter ( 5077): null': is not true.
I/flutter ( 5077):
I/flutter ( 5077): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 5077): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 5077): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 5077): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 5077):
I/flutter ( 5077): When the exception was thrown, this was the stack:
I/flutter ( 5077): #2 new FileImage (package:flutter/src/painting/image_provider.dart:532:14)
I/flutter ( 5077): #3 new Image.file (package:flutter/src/widgets/image.dart:254:16)
I/flutter ( 5077): #4 ImageAndFaces.build (package:visionappwork/main.dart:94:28)
I/flutter ( 5077): #5 StatelessElement.build (package:flutter/src/widgets/framework.dart:3789:28)
I/flutter ( 5077): #6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3736:15)
.........
Does anybody know what the problem is?
I tried anything I can think of, including trying to catch the 'ImageAndFaces' class constructor as it creates an instance, without any success.
I'm new to flutter and dart, so maybe it's a stupid mistake.
Thanks a lot!
The reason you're having a problem is that imageFile starts out null. Since it's being passed in to Image.file(imageFile, fit: BoxFit.cover) you're seeing the failure due to the assertion that the file passed to Image.file is not null.
You need to add some logic to check whether imageFile is null and do something different if it is.

Tried calling: ancestorStateOfType(Instance of 'TypeMatcher<NavigatorState>'

I am trying to call new page on tap of row item in the list view, I am very new to flutter
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(title: "My First Flutter App", home: new Home());
}
}
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: AppBar(
title: Text("Hello"),
backgroundColor: Colors.black,
),
body: WordPairState()._buildSugg(context));
}
}
class WordPairState extends State<RandomWordPair> {
final _suggetions = <WordPair>[];
final _bigText = const TextStyle(fontSize: 16);
#override
Widget build(BuildContext context) {
final _wordPair = WordPair.random();
// TODO: implement build
return Text(_wordPair.asPascalCase);
}
Widget _buildSugg(BuildContext ctx) {
return ListView.builder(
padding: const EdgeInsets.all(10),
itemBuilder: (context, i) {
if (i.isOdd) return Divider();
final count = i ~/ 2;
if (count >= _suggetions.length) {
_suggetions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggetions[count], count, ctx);
});
}
Widget _buildRow(WordPair wp, final count, BuildContext ctx) {
return ListTile(
subtitle: Text("List Sub title " + wp.toString()),
title: Text(
wp.asPascalCase,
style: _bigText,
),
onTap: () {
Route route = MaterialPageRoute(builder: (context) => SecondRoute());
Navigator.push(context, route);
});
}
I am getting an Error as follows maybe it's because of the wrong context but I don't know which context should I pass:
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (15113): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter (15113): The method 'ancestorStateOfType' was called on null.
I/flutter (15113): Receiver: null
I/flutter (15113): Tried calling: ancestorStateOfType(Instance of 'TypeMatcher')
I/flutter (15113):
I/flutter (15113): When the exception was thrown, this was the stack:
I/flutter (15113): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter (15113): #1 Navigator.of (package:flutter/src/widgets/navigator.dart:1376:19)
I/flutter (15113): #2 WordPairState._buildRow. (package:flutter_app/main.dart:99:19)
I/flutter (15113): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:513:14)
I/flutter (15113): #4 _InkResponseState.build. (package:flutter/src/material/ink_well.dart:568:30)
I/flutter (15113): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:120:24)
I/flutter (15113): #6 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
I/flutter (15113): #7 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:204:7)
I/flutter (15113): #8 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
I/flutter (15113): #9 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:20)
I/flutter (15113): #10 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:192:22)
I/flutter (15113): #11 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:149:7)
I/flutter (15113): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
I/flutter (15113): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
I/flutter (15113): #17 _invoke1 (dart:ui/hooks.dart:223:10)
I/flutter (15113): #18 _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5)
I/flutter (15113): (elided 3 frames from package dart:async)
I/flutter (15113):
I/flutter (15113): Handler: onTap
You have a bug/typo in the method
Widget _buildRow(WordPair wp, final count, BuildContext context) { // you named it ctx (and using context in implementation) which was causing the problem
return ListTile(
subtitle: Text("List Sub title " + wp.toString()),
title: Text(
wp.asPascalCase,
style: _bigText,
),
onTap: () {
Route route = MaterialPageRoute(builder: (context) => SecondRoute());
Navigator.push(context, route);
});
}

How to implement a SingleChildScrollView(with horizontal listview and vertical gridview) inside a TabBarView

I want to have a widget that scrolls vertically with few items on them. At the top of it there should be a horizontal ListView, followed up with gridview. And all this is inside a TabBarView.
I have tried wrapping the horizontal ListView and vertical gridview using SingleChildScrollView as suggested from other's StackOverflow question but it didn't work.
Widget build(BuildContext context) {
List tabs = <Tab>[
Tab(text: "Home"),
Tab(text: "Store"),
Tab(text: "Favourite")
];
return DefaultTabController(
length: 3,
child: Scaffold(
key: _scaffoldKey,
drawer: drawerSidebar(),
backgroundColor: Colors.grey[100],
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.notifications),
),
IconButton(
icon: Icon(Icons.message),
),
],
title: TextField(
controller: _filter,
decoration: new InputDecoration(
fillColor: Colors.white, filled: true, hintText: 'Search'),
),
bottom: TabBar(
// indicatorSize: TabBarIndicatorSize.tab,
tabs: tabs,
controller: _tabController,
),
),
body: TabBarView(
children: <Widget>[
SingleChildScrollView(
child:
Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Explore(), //horizontal listview
Expanded(
child: FreshFinds(), //vertical gridview.builder
),
],
)),
PageTwo(),
],
)));
}
This is the error i get when using SingleChildScrollView:
I/flutter (18049): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (18049): The following assertion was thrown during performLayout():
I/flutter (18049): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter (18049): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter (18049): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter (18049): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter (18049): space in the vertical direction.
I/flutter (18049): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter (18049): cannot simultaneously expand to fit its parent.
I/flutter (18049): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter (18049): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter (18049): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter (18049): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter (18049): constraints provided by the parent.
I/flutter (18049): The affected RenderFlex is:
I/flutter (18049): RenderFlex#46825 relayoutBoundary=up1 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (18049): The creator information is set to:
I/flutter (18049): Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#653c5] ← Semantics ← Listener ←
I/flutter (18049): _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#61b8a] ←
I/flutter (18049): _ScrollableScope ← _ScrollSemantics-[GlobalKey#7275d] ← RepaintBoundary ← CustomPaint ←
I/flutter (18049): RepaintBoundary ← ⋯
I/flutter (18049): The nearest ancestor providing an unbounded width constraint is:
I/flutter (18049): _RenderSingleChildViewport#72ad5 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (18049): creator: _SingleChildViewport ← IgnorePointer-[GlobalKey#653c5] ← Semantics ← Listener ←
I/flutter (18049): _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#61b8a] ←
I/flutter (18049): _ScrollableScope ← _ScrollSemantics-[GlobalKey#7275d] ← RepaintBoundary ← CustomPaint ←
I/flutter (18049): RepaintBoundary ← NotificationListener<ScrollNotification> ← ⋯
I/flutter (18049): parentData: <none> (can use size)
I/flutter (18049): constraints: BoxConstraints(w=454.7, h=680.4)
I/flutter (18049): size: MISSING
I/flutter (18049): See also: https://flutter.io/layout/
I/flutter (18049): If this message did not help you determine the problem, consider using debugDumpRenderTree():
I/flutter (18049): https://flutter.io/debugging/#rendering-layer
I/flutter (18049): http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
I/flutter (18049): If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
I/flutter (18049): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter (18049):
My result without using SingleChildScrollView
what I want
So i solved it using CustomScrollView with Slivers
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("Settings"),
),
body: Container(
child: CustomScrollView(
slivers: <Widget>[
SliverList(
delegate: SliverChildListDelegate(<Widget>[
Container(
child: new Image.asset(
"images/product.jpg",
fit: BoxFit.fitWidth,
),
),
])),
FreshFinds()
],
),
),
);
}
//Freshfinds.dart
Widget build(BuildContext context) {
return SliverGrid(
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
return FutureBuilder(
future: fetchdata(index),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData)
return buildfake(index);
else
return buildcard(snapshot.data, index);
},
);
}, childCount: 20),
);
}

How to properly set value of DropdownButton using Bloc in Flutter?

I'm new in Bloc programming pattern and I'm having an issue when using it in with Dropdown
That's in my bloc class:
final _dropDown = BehaviorSubject<String>();
Stream<String> get dropDownStream => _dropDown.stream;
Sink<String> get dropDownSink => _dropDown.sink;
final _dropdownValues = BehaviorSubject<List<String>>(seedValue: [
'One',
'Two',
'Three',
'Four',
].toList());
Stream<List<String>> get dropdownValuesStream => _dropdownValues.stream;
In my widget page I added the following dropdown widget so that everything is handled by the Bloc class:
StreamBuilder<List<String>>(
stream: _exampleBloc.dropdownValuesStream,
builder: (BuildContext contextValues, AsyncSnapshot snapshotValues) {
return StreamBuilder<String>(
stream: _exampleBloc.dropDownStream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
return InputDecorator(
decoration: InputDecoration(
icon: const Icon(Icons.color_lens),
labelText: 'DropDown',
),
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: snapshot.data,
onChanged: (String newValue) => _exampleBloc.dropDownSink.add(newValue),
items: snapshotValues.data != null ? snapshotValues.data.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList() : <String>[''].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
},
);
},
),
But doing like that, I get this error when setting the value (value: snapshot.data) of the DropdownButton:
I/flutter ( 5565): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 5565): The following assertion was thrown building StreamBuilder<String>(dirty, state:
I/flutter ( 5565): _StreamBuilderBaseState<String, AsyncSnapshot<String>>#70482):
I/flutter ( 5565): 'package:flutter/src/material/dropdown.dart': Failed assertion: line 514 pos 15: 'items == null ||
I/flutter ( 5565): value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not
I/flutter ( 5565): true.
I/flutter ( 5565):
I/flutter ( 5565): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 5565): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 5565): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 5565): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 5565):
I/flutter ( 5565): When the exception was thrown, this was the stack:
I/flutter ( 5565): #2 new DropdownButton (package:flutter/src/material/dropdown.dart:514:15)
I/flutter ( 5565): #3 _ExamplePageState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:financeiro_mobile/src/ui/exemple/example_page.dart:129:42)
I/flutter ( 5565): #4 StreamBuilder.build (package:flutter/src/widgets/async.dart:423:74)
I/flutter ( 5565): #5 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 5565): #6 StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 5565): #7 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 5565): #8 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 5565): #9 StatefulElement.update (package:flutter/src/widgets/framework.dart:3878:5)
I/flutter ( 5565): #10 Element.updateChild (package:flutter/src/widgets/framework.dart:2742:15)
I/flutter ( 5565): #11 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16)
I/flutter ( 5565): #12 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 5565): #13 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2286:33)
I/flutter ( 5565): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:676:20)
I/flutter ( 5565): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 5565): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 5565): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 5565): #18 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 5565): #19 _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 5565): #20 _drawFrame (dart:ui/hooks.dart:143:3)
I/flutter ( 5565): (elided 2 frames from class _AssertionError)
I tried a lot of ideas like checking if snapshotValues.data is not null when setting. I know that the value has to be something from the list or null. But no logic that I put there makes this error go away.
If I set the value to null, it works, but then the selected value doesn't show.
Am I doing this wrong? Is there a better way that works? How can I solve this issue?
Thanks!
I solved it using two stream in the bloc, one for the list of elemtns and the other for the value. So in ther build, you need two chained StreamBuilders and when u got both snapshots with data, you load the build. Like that:
Widget _holdingDropDown() {
return StreamBuilder(
stream: bloc.holding,
builder: (BuildContext context, AsyncSnapshot<Holding> snapshot) {
return Container(
child: Center(
child: snapshot.hasData
? StreamBuilder(
stream: bloc.obsHoldingList,
builder: (BuildContext context,
AsyncSnapshot<List<Holding>> holdingListSnapshot) {
return holdingListSnapshot.hasData ?
DropdownButton<Holding>(
value: snapshot.data,
items: _listDropDownHoldings,
onChanged: (Holding h) {
_changeDropDownItemHolding(h);
},
): CircularProgressIndicator();
},
)
: CircularProgressIndicator(),
),
);
});
}
I use the circular progress indicator to return if I don't have the snapshot with data.
I hope I have been helpful.
That's because you are using a StreamBuilder, so at the first time your snapshot is empty, you have to do a validation :
return snapshot.hasData ?
InputDecorator(
decoration: InputDecoration(
icon: const Icon(Icons.color_lens),
labelText: 'DropDown',
),
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: snapshot.data,
onChanged: (String newValue) => _exampleBloc.dropDownSink.add(newValue),
items: snapshotValues.data != null ? snapshotValues.data.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList() : SizedBox(height: 0.0)
),
) : SizedBox(height: 0.0);
Display an empty widget SizedBox(height: 0.0) or a CircleProgressIndicator
I use just Bloc for setting and changing Dropdown values, without using stream (in example I use two dropdowns with different values). Below part of real script from my app:
class LangsInput extends StatelessWidget {
const LangsInput({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return BlocBuilder<WordGroupFormBloc, WordGroupFormState>(
buildWhen: (previous, current) => previous != current,
builder: (context, state) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
DropdownButton<String>(
value: state.langStudy.value,
icon: const Icon(Icons.arrow_drop_down),
elevation: 16,
onChanged: (String? newValue) {
context.read<WordGroupFormBloc>().add(LangStudyChanged(langStudy: newValue as String));
},
items: getLanguageList(),
),
DropdownButton<String>(
value: state.langTransl.value,
icon: const Icon(Icons.arrow_drop_down),
elevation: 16,
onChanged: (String? newValue) {
context.read<WordGroupFormBloc>().add(LangTranslChanged(langTransl: newValue as String));
},
items: getLanguageList(),
),
]
);
}
);
}
}
and part of script example from bloc:
void _onLangStudyChanged(LangStudyChanged event, Emitter<WordGroupFormState> emit) {
final langStudy = LangStudy.dirty(event.langStudy);
emit(state.copyWith(
langStudy: langStudy.valid ? langStudy : LangStudy.pure(event.langStudy),
status: Formz.validate([langStudy]),
));
}

Resources