Related
I am trying to user Streambuilder to display gridview, but it return this error, I am calling the method classList() to container in scaffold body
database = FirebaseDatabase.instance
I want to show classData, show 0,1,2..etc I want to show ('className','classSection' in one button per child) in gridview as RaisedButtons
I get this error when the code below is executed
I/flutter ( 5433): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 5433): The following NoSuchMethodError was thrown building HomePage(dirty, state: _HomePage#055be):
I/flutter ( 5433): The method 'split' was called on null.
I/flutter ( 5433): Receiver: null
I/flutter ( 5433): Tried calling: split("/")
I/flutter ( 5433):
I/flutter ( 5433): When the exception was thrown, this was the stack:
I/flutter ( 5433): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter ( 5433): #1 DatabaseReference.child (file:///G:/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_database-2.0.3/lib/src/database_reference.dart:24:58)
I/flutter ( 5433): #2 _HomePage.classList (package:barcode_scan_example/home_page.dart:169:44)
I/flutter ( 5433): #3 _HomePage.build (package:barcode_scan_example/home_page.dart:265:30)
I/flutter ( 5433): #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:3825:27)
I/flutter ( 5433): #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3736:15)
I/flutter ( 5433): #6 Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
I/flutter ( 5433): #7 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3716:5)
I/flutter ( 5433): #8 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3864:11)
I/flutter ( 5433): #9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3711:5)
I/flutter ( 5433): #10 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
I/flutter ( 5433): #11 Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
I/flutter ( 5433): #12 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
I/flutter ( 5433): #13 Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
I/flutter ( 5433): #14 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2273:33)
I/flutter ( 5433): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
I/flutter ( 5433): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:268:5)
I/flutter ( 5433): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:988:15)
I/flutter ( 5433): #18 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:928:9)
I/flutter ( 5433): #19 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:840:5)
I/flutter ( 5433): #23 _invoke (dart:ui/hooks.dart:209:10)
I/flutter ( 5433): #24 _drawFrame (dart:ui/hooks.dart:168:3)
I/flutter ( 5433): (elided 3 frames from package dart:async)
classList() {
StreamBuilder(
stream:
database.reference().child('user').child(userUid).child('classData').orderByKey().onValue,
builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
if (snapshot.data.snapshot.value != null) {
Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
List<dynamic> list = map.values.toList();
print("list is : $list");
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),
itemCount: list.length,
padding: EdgeInsets.all(2.0),
itemBuilder: (BuildContext context, int index) {
print("print job ${list[index]["className"]}");
return Container(
child: RaisedButton(
onPressed: null,
child: Text(
"${list[index]["className"]}\n ${list[index]["classSection"]}"),
),
padding: EdgeInsets.all(2.0),
);
},
);
} else {
return Container(
child: Center(
child: Text(
"There's no Class registered in the system",
style: TextStyle(fontSize: 20.0, color: Colors.grey),
textAlign: TextAlign.center,
)));
}
} else {
return CircularProgressIndicator();
}
});
}
the entire dart file
import 'package:flutter/material.dart';
import 'auth.dart';
import 'auth_provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/services.dart';
import 'make_class.dart';
import 'dart:async';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:firebase_database/firebase_database.dart';
import 'qr_screen.dart';
class HomePage extends StatefulWidget {
#override
_HomePage createState() => _HomePage();
}
enum ScaffoldType { student, lecturer }
ScaffoldType _scaffoldType = ScaffoldType.lecturer;
class _HomePage extends State<HomePage> {
final FirebaseDatabase database = FirebaseDatabase.instance;
String barcode = "";
String userUid;
var userClass;
Future<void> _signOut(BuildContext context) async {
try {
final BaseAuth auth = AuthProvider.of(context).auth;
await auth.signOut();
} catch (e) {
print(e);
}
}
#override
void initState() {
super.initState();
userUi();
setState(() async* {
FirebaseDatabase database;
database = FirebaseDatabase.instance;
database.setPersistenceEnabled(true);
database.setPersistenceCacheSizeBytes(10000000);
});
}
Future reUser() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
print(user.uid);
var userUid = user.uid;
var userWho = await database
.reference()
.child('user')
.child(userUid)
.once()
.then((DataSnapshot snapshot) {
Map<dynamic, dynamic> data = snapshot.value;
var isL = data.values.toList();
print(isL[1]);
print(data.values);
if (isL[1].toString().toLowerCase() == "true") {
_scaffoldType = ScaffoldType.lecturer;
print('lecturer');
} else if (isL[1].toString().toLowerCase() == "false") {
_scaffoldType = ScaffoldType.student;
print("student");
}
});
// print(userWho);
}
userUi() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
print(user.uid);
return user.uid;
}
classList(userUid) {
print(userUid);
StreamBuilder(
stream:
database.reference().child('user').child(userUid).child('classData').orderByKey().onValue,
builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
if (snapshot.data.snapshot.value != null) {
Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
List<dynamic> list = map.values.toList();
print("list is : $list");
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),
itemCount: list.length,
padding: EdgeInsets.all(2.0),
itemBuilder: (BuildContext context, int index) {
print("print job ${list[index]["className"]}");
return Container(
child: RaisedButton(
onPressed: (){},
child: Text(
"${list[index]["className"]}\n ${list[index]["classSection"]}"),
),
padding: EdgeInsets.all(2.0),
);
},
);
} else {
return Container(
child: Center(
child: Text(
"There's no Class registered in the system",
style: TextStyle(fontSize: 20.0, color: Colors.grey),
textAlign: TextAlign.center,
)));
}
} else {
return CircularProgressIndicator();
}
});
}
#override
Widget build(BuildContext context) {
// var userUid = userUi();
reUser();
return Scaffold(
appBar: AppBar(
title: Text('Welcome'),
actions: <Widget>[
FlatButton(
child: Icon(Icons.exit_to_app),
onPressed: () => _signOut(context),
)
],
),
bottomNavigationBar: BottomAppBar(
notchMargin: 8.0,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Padding(
padding: const EdgeInsets.fromLTRB(35, 0, 35, 0),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: buttonBelow(),
),
Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: buttonBelow2(),
),
],
),
),
),
shape: CircularNotchedRectangle(),
),
resizeToAvoidBottomInset: true,
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: Container(
height: 80,
width: 80,
child: FittedBox(
child: FloatingActionButton(
onPressed: scan,
child: Icon(
Icons.camera,
size: 35,
),
elevation: 2.0,
),
),
),
body: Container(child: classList(userUi()),),
);
}
List<Widget> buttonBelow() {
if (_scaffoldType == ScaffoldType.lecturer) {
return <Widget>[
FlatButton(
child: Icon(
Icons.add_circle,
semanticLabel: "Add Class",
size: 45,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MakeClass()),
);
},
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(180)),
),
Text("Add Class")
];
} else {
return <Widget>[
Opacity(
opacity: 0,
child: FlatButton(
onPressed: () {},
child: Icon(
Icons.add_circle,
semanticLabel: "Add Class",
size: 45,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(180)),
),
),
Opacity(opacity: 0, child: Text("Add Class"))
];
}
}
List<Widget> buttonBelow2() {
if (_scaffoldType == ScaffoldType.lecturer) {
return <Widget>[
FlatButton(
child: Icon(
Icons.blur_on,
semanticLabel: "QRCode",
size: 45,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => QrScreen()),
);
},
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(180)),
),
Text("QRCode")
];
}
}
Future scan() async {
try {
String barcode = await BarcodeScanner.scan();
setState(() => this.barcode = barcode);
} on PlatformException catch (e) {
if (e.code == BarcodeScanner.CameraAccessDenied) {
setState(() {
this.barcode = 'The user did not grant the camera permission!';
});
} else {
setState(() => this.barcode = 'Unknown error: $e');
}
} on FormatException {
setState(() => this.barcode =
'null (User returned using the "back"-button before scanning anything. Result)');
} catch (e) {
setState(() => this.barcode = 'Unknown error: $e');
}
}
}
Main problem is when we pass blank or null string in ".child()" method of firebase, it will give us split("/") error because internally it will try to split from string and get try to get data
from it.
Now the problem in your code is you are calling "classList(userUid)" in the widget override method before the data come from firebase userid with use of StreamBuilder() but the userUid is blank and as i said above,
firebase will give us split("/") error if we pass blank or null in that ".child()" method.
So the conclusion is we have to wait for firebase userid until we get it from async result because to get firebase userid which is async task and we have to wait for that until result come with using await keyword.
So Here is the answer, how to do that:
You have to replace your body portion in widget with the use of future<> such as below:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Welcome'),
actions: <Widget>[
FlatButton(
child: Icon(Icons.exit_to_app),
onPressed: () => _signOut(context),
)
],
),
bottomNavigationBar: BottomAppBar(
notchMargin: 8.0,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Padding(
padding: const EdgeInsets.fromLTRB(35, 0, 35, 0),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: buttonBelow(),
),
Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: buttonBelow2(),
),
],
),
),
),
shape: CircularNotchedRectangle(),
),
resizeToAvoidBottomInset: true,
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: Container(
height: 80,
width: 80,
child: FittedBox(
child: FloatingActionButton(
onPressed: scan,
child: Icon(
Icons.camera,
size: 35,
),
elevation: 2.0,
),
),
),
body: new FutureBuilder<FirebaseUser>(
future: FirebaseAuth.instance.currentUser(),
builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return new Container(child: classList(snapshot.data.uid));
}
else {
return new Text('Loading...');
}
},
),
);
}
Also the best practice is that you have to get firebase userid only in "initState()" method which will call only once during lifecycle. so declare "FirebaseUser user" globally in your class and then call your "userUi()"
in only "initState()" method.
The method 'split' was called on null.
This type of exceptions occurs whenever you are referencing a path that doesn't exist. So make sure the path of your firebase database is correct.
This is the variable initialisation
var displayResult = '';
Here is the on press code
Padding(
padding: EdgeInsets.all(5.0),
child: Row(
children: <Widget>[
Expanded(
child: RaisedButton(
color: Theme
.of(context)
.primaryColor,
textColor: Theme
.of(context)
.primaryColorLight,
child: Text("calculate"),
onPressed: () {
setState(() {
this.displayResult = _calculateTotalReturn();
});
},
)),
This the function Im trying to call
String _calculateTotalReturn() {
setState(() {
double principle = double.parse(principleController.text);
double roi = double.parse(roiController.text);
double term = double.parse(termController.text);
double tap = principle + (principle * roi * term) / 100;
String result = "After $term years, your investment will worth $tap $_currentItemSelected";
return result;
});
}
This is the error I'm getting
Performing hot reload...
Syncing files to device iPhone XR...
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building SIForm(dirty, dependencies:
flutter: [_LocalizationsScope-[GlobalKey#4c1f9], _InheritedTheme], state: _SIFormState#b2966):
flutter: 'package:flutter/src/widgets/text.dart': Failed assertion: line 237 pos 15: 'data != null': is not
flutter: 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: When the exception was thrown, this was the stack:
flutter: #2 new Text (package:flutter/src/widgets/text.dart:237:15)
flutter: #3 _SIFormState.build (package:simple_cal/main.dart:153:24)
flutter: #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:3825:27)
flutter: #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3736:15)
flutter: #6 Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
flutter: #7 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2273:33)
flutter: #8 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
flutter: #9 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:268:5)
flutter: #10 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:988:15)
flutter: #11 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:928:9)
flutter: #12 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:749:7)
flutter: #14 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
flutter: #15 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
flutter: #16 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
flutter: (elided 3 frames from class _AssertionError and package dart:async)
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
Reloaded 1 of 432 libraries in 641ms.
This is the complete main.dart file
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
Widget MyApp() {
return MaterialApp(
title: 'Simple Intrest app',
home: SIForm (),
theme: ThemeData(
primaryColor: Colors.deepPurple,
accentColor: Colors.deepPurpleAccent
),
);
}
class SIForm extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _SIFormState ();
}
}
class _SIFormState extends State<SIForm> {
var _currencies = ["INR", "USD", "CAD"];
var _currentItemSelected = "INR";
var displayResult = '';
TextEditingController principleController = TextEditingController();
TextEditingController roiController = TextEditingController();
TextEditingController termController = TextEditingController();
#override
Widget build(BuildContext context) {
TextStyle textStyle = Theme
.of(context)
.textTheme
.title;
return Scaffold(
appBar: AppBar(
title: Text("Simple Interest Calc"),
),
body: Container(padding: EdgeInsets.only(top: 50.0),
child: ListView(
children: <Widget>[
Padding(
padding: EdgeInsets.all(5.0),
child: TextField(
keyboardType: TextInputType.number,
controller: principleController,
decoration: InputDecoration(
labelText: 'principle',
hintText: '0.00',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0)
)
),
)),
Padding(
padding: EdgeInsets.all(5.0),
child: TextField(
controller: roiController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Rate of Interest',
hintText: '0.00',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0)
)
),
)),
Padding(
padding: EdgeInsets.all(5.0),
child: Row(
children: <Widget>[
Expanded(child: TextField(
controller: termController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Terms',
hintText: '%',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0)
)
),
)),
Container(width: 10.0),
Expanded(
child: DropdownButton<String>(
items: _currencies.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
value: _currentItemSelected,
onChanged: (val) {
_ondropDownChange(val);
},),
),
],
)),
Padding(
padding: EdgeInsets.all(5.0),
child: Row(
children: <Widget>[
Expanded(
child: RaisedButton(
color: Theme
.of(context)
.primaryColor,
textColor: Theme
.of(context)
.primaryColorLight,
child: Text("calculate"),
onPressed: () {
setState(() {
this.displayResult = _calculateTotalReturn();
});
},
)),
Container(width: 5.0),
Expanded(
child: RaisedButton(
color: Theme
.of(context)
.accentColor,
textColor: Theme
.of(context)
.primaryColorLight,
child: Text("Reset"),
onPressed: () {
setState(() {
// _reset();
});
}
)),
],
)),
Padding(
padding: EdgeInsets.all(5.0),
child: Text(this.displayResult),
)
],
),
),
);
}
void _ondropDownChange(String value) {
setState(() {
this._currentItemSelected = value;
});
}
String _calculateTotalReturn() {
setState(() {
double principle = double.parse(principleController.text);
double roi = double.parse(roiController.text);
double term = double.parse(termController.text);
double tap = principle + (principle * roi * term) / 100;
String result = "After $term years, your investment will worth $tap $_currentItemSelected";
return result;
});
}
void _reset() {
setState(() {
this.principleController.text = " ";
this.roiController.text = " ";
this.termController.text = " ";
this.displayResult = " ";
});
}
}
You should get rid of the setState in _calculateTotalReturn. The return result; there is returning from the inline function that you give to setState and _calculateTotalReturn actually returns null.
I am trying to make a flutter app. Recently, I have learned how to use hero with two different buttons which all have the same destination. So, I tried to use hero with infinitely creatable containers. This is what I came up with:
import 'package:flutter/material.dart';
void main() => runApp(MainPage());
class MainPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.white,
body: Column(children: <Widget>[
Body(),
])));
}
}
class Body extends StatefulWidget {
#override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
final String open1 = 'open';
int count = 1;
#override
Widget build(BuildContext context) {
print(count);
List cards = List.generate(count, (int i) => RCard(count));
return Expanded(
child: Container(
child: NotificationListener<OverscrollIndicatorNotification>(
onNotification: (OverscrollIndicatorNotification overscroll) {
overscroll.disallowGlow();
},
child: PageView.builder(
reverse: true,
pageSnapping: false,
controller: PageController(viewportFraction: 0.85),
itemCount: count,
itemBuilder: (context, i) {
if (i == 0) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page(
open: open1,
)),
);
count++;
},
child: Hero(
tag: open1,
child: Padding(
padding: EdgeInsets.only(
left:
MediaQuery.of(context).size.height *
0.015,
right:
MediaQuery.of(context).size.height *
0.015,
top: MediaQuery.of(context).size.width *
0.08,
bottom:
MediaQuery.of(context).size.width *
0.15),
child: Material(
borderRadius:
BorderRadius.circular(40.0),
color: Colors.white,
elevation: 8.0,
child: InkWell(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.add,
size: 30.0,
color: Colors.black,
)
]),
)))));
} else {
return cards[i];
}
}))));
}
}
class RCard extends StatefulWidget {
final int count;
RCard(this.count);
#override
RCardState createState() => RCardState();
}
class RCardState extends State<RCard> {
int count;
String open2;
#override
void initState() {
super.initState();
count = widget.count;
open2 = 'open$count';
}
#override
Widget build(BuildContext context) {
return Hero(
tag: open2,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page(
open: open2,
)),
);
},
child: Padding(
padding: EdgeInsets.only(
left: MediaQuery.of(context).size.height * 0.015,
right: MediaQuery.of(context).size.height * 0.015,
top: MediaQuery.of(context).size.width * 0.08,
bottom: MediaQuery.of(context).size.width * 0.15),
child: Material(
borderRadius: BorderRadius.circular(40.0),
color: Colors.white,
elevation: 8.0,
child: Padding(
padding:
EdgeInsets.all(MediaQuery.of(context).size.width * 0.15),
)),
)),
);
}
}
class Page extends StatelessWidget {
final String open;
Page({this.open});
#override
Widget build(BuildContext context) {
return GestureDetector(
child: Hero(
tag: open,
child: Material(
child: Center(child: Text('New page')),
)),
onTap: () {
Navigator.pop(context);
},
);
}
}
But, when I create a second container and press on it, It will give a black screen and get an error message in my debug console saying:
flutter: ══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during a scheduler callback:
flutter: There are multiple heroes that share the same tag within a subtree.
flutter: Within each subtree for which heroes are to be animated (typically a PageRoute subtree), each Hero
flutter: must have a unique non-null tag.
flutter: In this case, multiple heroes had the following tag: opennull
flutter: Here is the subtree for one of the offending heroes:
flutter: # Hero(tag: opennull, state: _HeroState#f299c)
flutter: # └KeyedSubtree-[GlobalKey#45266]
flutter: # └GestureDetector
flutter: # └RawGestureDetector(state: RawGestureDetectorState#98814(gestures: [tap]))
flutter: # └_GestureSemantics(renderObject: RenderSemanticsGestureHandler#59110)
flutter: # └Listener(listeners: [down], behavior: deferToChild, renderObject: RenderPointerListener#5cfa6)
flutter: # └Padding(padding: EdgeInsets(13.4, 33.1, 13.4, 62.1), renderObject: RenderPadding#ab11d)
flutter: # └Material(type: canvas, elevation: 8.0, color: Color(0xffffffff), borderRadius: circular(40.0), state: _MaterialState#a511a)
flutter: # └_MaterialInterior(duration: 200ms, shape: RoundedRectangleBorder(BorderSide(Color(0xff000000), 0.0, BorderStyle.none), BorderRadius.circular(40.0)), elevation: 8.0, color: Color(0xffffffff), shadowColor: Color(0xff000000), state: _MaterialInteriorState#6412f(ticker inactive))
flutter: # └PhysicalShape(clipper: ShapeBorderClipper, elevation: 8.0, color: Color(0xffffffff), shadowColor: Color(0xff000000), renderObject: RenderPhysicalShape#1b504)
flutter: # └_ShapeBorderPaint
flutter: # └CustomPaint(renderObject: RenderCustomPaint#94831)
flutter: # └NotificationListener<LayoutChangedNotification>
flutter: # └_InkFeatures-[GlobalKey#8ef37 ink renderer](renderObject: _RenderInkFeatures#670e3)
flutter: # └AnimatedDefaultTextStyle(duration: 200ms, debugLabel: (englishLike body1 2014).merge(blackCupertino body1), inherit: false, color: Color(0xdd000000), family: .SF UI Text, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip, state: _AnimatedDefaultTextStyleState#9cb8b(ticker inactive))
flutter: # └DefaultTextStyle(debugLabel: (englishLike body1 2014).merge(blackCupertino body1), inherit: false, color: Color(0xdd000000), family: .SF UI Text, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip)
flutter: # └Padding(padding: EdgeInsets.all(62.1), renderObject: RenderPadding#0a02b)
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 Hero._allHeroesFor.visitor.<anonymous closure>
package:flutter/…/widgets/heroes.dart:210
flutter: #1 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:220
flutter: #2 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #3 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #4 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #5 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #6 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #7 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #8 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #9 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #10 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #11 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #12 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #13 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #14 List.forEach (dart:core/runtime/libgrowable_array.dart:278:8)
flutter: #15 SliverMultiBoxAdaptorElement.visitChildren
package:flutter/…/widgets/sliver.dart:1175
flutter: #16 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #17 MultiChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4948
flutter: #18 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #19 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #20 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #21 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #22 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #23 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #24 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #25 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #26 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #27 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #28 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #29 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #30 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #31 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #32 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #33 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #34 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #35 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #36 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #37 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #38 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #39 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #40 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #41 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #42 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #43 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #44 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #45 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #46 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #47 MultiChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4948
flutter: #48 Hero._allHeroesFor.visitor
flutter: #49 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #50 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #51 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #52 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #53 MultiChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4948
flutter: #54 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #55 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #56 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #57 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #58 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #59 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #60 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #61 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #62 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #63 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #64 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #65 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #66 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #67 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #68 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #69 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #70 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #71 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #72 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #73 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #74 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #75 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #76 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #77 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #78 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #79 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #80 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #81 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #82 Element.visitChildElements
package:flutter/…/widgets/framework.dart:2686
flutter: #83 Hero._allHeroesFor
package:flutter/…/widgets/heroes.dart:227
flutter: #84 HeroController._startHeroTransition
package:flutter/…/widgets/heroes.dart:655
flutter: #85 HeroController._maybeStartHeroTransition.<anonymous closure>
package:flutter/…/widgets/heroes.dart:630
flutter: #86 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback
package:flutter/…/scheduler/binding.dart:990
flutter: #87 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame
package:flutter/…/scheduler/binding.dart:938
flutter: #88 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame
package:flutter/…/scheduler/binding.dart:842
flutter: #89 _invoke (dart:ui/hooks.dart:154:13)
flutter: #90 _drawFrame (dart:ui/hooks.dart:143:3)
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
How anyone please help???
Instead of doing - List.generate in build. Simply Pass RCard directly in PageView.builder
working Code:
import 'package:flutter/material.dart';
void main() => runApp(MainPage());
class MainPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.white,
body: Column(children: <Widget>[
Body(),
])));
}
}
class Body extends StatefulWidget {
#override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
final String open1 = 'open';
int count = 1;
#override
Widget build(BuildContext context) {
print(count);
return Expanded(
child: Container(
child: NotificationListener<OverscrollIndicatorNotification>(
onNotification: (OverscrollIndicatorNotification overscroll) {
overscroll.disallowGlow();
},
child: PageView.builder(
reverse: true,
pageSnapping: false,
controller: PageController(viewportFraction: 0.85),
itemCount: count,
itemBuilder: (context, i) {
if (i == 0) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page(
open: open1,
)),
);
count++;
},
child: Hero(
tag: open1,
child: Padding(
padding: EdgeInsets.only(
left:
MediaQuery.of(context).size.height *
0.015,
right:
MediaQuery.of(context).size.height *
0.015,
top: MediaQuery.of(context).size.width *
0.08,
bottom:
MediaQuery.of(context).size.width *
0.15),
child: Material(
borderRadius:
BorderRadius.circular(40.0),
color: Colors.white,
elevation: 8.0,
child: InkWell(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.add,
size: 30.0,
color: Colors.black,
)
]),
)))));
} else {
return RCard(i);
}
}))));
}
}
class RCard extends StatefulWidget {
final int count;
RCard(this.count);
#override
RCardState createState() => RCardState();
}
class RCardState extends State<RCard> {
int count;
String open2;
#override
void initState() {
super.initState();
count = widget.count;
open2 = 'open$count';
}
#override
Widget build(BuildContext context) {
return Hero(
tag: open2,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page(
open: open2,
)),
);
},
child: Padding(
padding: EdgeInsets.only(
left: MediaQuery.of(context).size.height * 0.015,
right: MediaQuery.of(context).size.height * 0.015,
top: MediaQuery.of(context).size.width * 0.08,
bottom: MediaQuery.of(context).size.width * 0.15),
child: Material(
borderRadius: BorderRadius.circular(40.0),
color: Colors.white,
elevation: 8.0,
child: Padding(
padding:
EdgeInsets.all(MediaQuery.of(context).size.width * 0.15),
)),
)),
);
}
}
class Page extends StatelessWidget {
final String open;
Page({this.open});
#override
Widget build(BuildContext context) {
return GestureDetector(
child: Hero(
tag: open,
child: Material(
child: Center(child: Text('New page')),
)),
onTap: () {
Navigator.pop(context);
},
);
}
}
I'm new with flutter & just learned how to retrieve data from firestore & did some UI. Right now I have 2 problems;
1- This is a Setting Page which has CustomScrollView contains ScrollController for the controller.
SettingsPage
The controller working fine with this code
class _SettingsPageState extends State<SettingsPage> {
ScrollController _scrollController;
#override
void initState() {
super.initState();
_scrollController = new ScrollController();
_scrollController.addListener(() => setState(() {}));
}
#override
void dispose() {
_scrollController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: Shared.firestore.collection('client').document(Shared.firebaseUser.uid).snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return Scaffold(
backgroundColor: Colors.grey[50],
body: Stack(
children: <Widget>[
CustomScrollView(
controller: _scrollController,
slivers: <Widget>[
SliverAppBar(
expandedHeight: 140.0,
pinned: true,
),
SliverFillRemaining(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
flex: 8,
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.white,
),
child: Padding(
padding: EdgeInsets.only(
left: 18.0,
top: 18.0,
),
child: Row(
children: <Widget>[
Text(
"Account",
style: TextStyle(
color: Colors.blue[700],
fontSize: 15,
fontWeight: FontWeight.w500,
),
),
],
),
),
),
Container(
decoration: BoxDecoration(
color: Colors.white,
),
child: ListTile(
onTap: () {},
contentPadding: EdgeInsets.only(left: 18.0),
title: Text(
"+${snapshot.data['countryCode']} ${snapshot.data['phoneNumber']}",
style: TextStyle(fontSize: 16),
),
subtitle: Row(
children: <Widget>[
Text(
"Phone Number",
style: TextStyle(
fontSize: 12,
),
),
],
),
),
),
],
),
),
],
),
),
],
),
],
),
);
},
);
}
}
but this error happened
I/flutter ( 8691): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 8691): The following NoSuchMethodError was thrown building StreamBuilder<DocumentSnapshot>(dirty, state:
I/flutter ( 8691): _StreamBuilderBaseState<DocumentSnapshot, AsyncSnapshot<DocumentSnapshot>>#7db43):
I/flutter ( 8691): The method '[]' was called on null.
I/flutter ( 8691): Receiver: null
I/flutter ( 8691): Tried calling: []("countryCode")
I/flutter ( 8691):
I/flutter ( 8691): When the exception was thrown, this was the stack:
I/flutter ( 8691): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter ( 8691): #1 _SettingsPageState.build.<anonymous closure> (package:silkwallet/page/settings.dart:81:54)
I/flutter ( 8691): #2 StreamBuilder.build (package:flutter/src/widgets/async.dart:423:74)
I/flutter ( 8691): #3 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 8691): #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 8691): #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 8691): #6 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8691): #7 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5)
I/flutter ( 8691): #8 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3848:11)
I/flutter ( 8691): #9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5)
I/flutter ( 8691): #10 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8691): #11 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 8691): #12 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16)
I/flutter ( 8691): #13 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8691): #14 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5)
I/flutter ( 8691): #15 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3848:11)
I/flutter ( 8691): #16 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5)
I/flutter ( 8691): #17 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8691): #18 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 8691): #19 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4860:14)
I/flutter ( 8691): #20 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8691): #21 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 8691): #22 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16)
I/flutter ( 8691): #23 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8691): #24 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5)
I/flutter ( 8691): #25 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5)
I/flutter ( 8691): #26 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8691): #27 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
.
.
.
I/flutter ( 8691): #135 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 8691): #136 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 8691): #137 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 8691): #138 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 8691): #139 _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 8691): #140 _drawFrame (dart:ui/hooks.dart:143:3)
2- After some research for this error, I add connectionState condition inside StreamBuilder which solved above problem
this is the new code, i put the Scaffold inside active connectionState
class _SettingsPageState extends State<SettingsPage> {
ScrollController _scrollController;
#override
void initState() {
super.initState();
_scrollController = new ScrollController();
_scrollController.addListener(() => setState(() {}));
}
#override
void dispose() {
_scrollController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: Shared.firestore.collection('client').document(Shared.firebaseUser.uid).snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
return Scaffold(
backgroundColor: Colors.grey[50],
body: Stack(
.
.
.
),
);
} else if (snapshot.connectionState == ConnectionState.waiting) {
return Container(child: Center(child: CircularProgressIndicator()));
} else {
return Container(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(Icons.warning),
),
Text('Error in loadind data')
],
),
);
}
},
);
}
}
and I realized that when I scrolled the connectionState will change to waiting and the ScrollController not working under this state as shown in the image below
ScrollController: page keep flashing when try to scroll
The reason I want to use the ScrollController because I want to add FloatingActionButton inside Positioned which will scroll along & disappear when reach certain position, here's the image with FloatingActionButton
NoSuchMethodError the method was called on null errors are usually thrown when the method that you're trying to call from the object is yet to be initialized. The error seems to be coming from snapshot.data['countryCode']. What you can do here is add a null-check on snapshot before displaying the data.
if (snapshot != null && snapshot.hasData) {
// Display data
} else {
// Display circular progress...
}
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]),
));
}