Flutter - The getter 'length' was called on null - android

I am trying to develop a flutter app. This flutter is creating teams for a card game. After the creation of the team, the points could be counted through the, so that you don't have to think about how many points everybody has.
But I got an exception, where I know where the exception and what it means, but i do not have any clue how i could solve the problem. I hope some of you guys could help me.
This is the code where the error is thrown:
import 'package:flutter/material.dart';
class Punktezaehler extends StatefulWidget{
final List<String> spieler_namen;
Punktezaehler(this.spieler_namen);
#override
State<StatefulWidget> createState() => new _Punktezaehler(this.spieler_namen);
}
class _Punktezaehler extends State<Punktezaehler>{
final List<String> spieler_namen;
_Punktezaehler(this.spieler_namen);
List<int> punkteanzahl_teamEins;
List<int> punkteanzahl_teamZwei;
#override
Widget build(BuildContext context) {
var spieler1 = spieler_namen[0].substring(0,3);
var spieler2 = spieler_namen[1].substring(0,3);
var spieler3 = spieler_namen[2].substring(0,3);
var spieler4 = spieler_namen[3].substring(0,3);
return new Scaffold(
appBar: new AppBar(
automaticallyImplyLeading: false,
title: new Text("$spieler1 & $spieler2 vs" +" $spieler3 & $spieler4"),
actions: <Widget>[
],
),
body: Container(
child: new Row(
children: <Widget>[
new Column(
children: <Widget>[
new IconButton(
icon: Icon(Icons.exposure_plus_2),
onPressed: () => punkte_hinzuzaehlen(1, 2)
)
],
),
new Column(
children: <Widget>[
//new FlatButton(onPressed: () => print(punkteanzahl_teamEins.length), child: new Text("Punkte")),
ListView.builder(
itemCount: punkteanzahl_teamEins.length, //--> Error is thrown here
itemBuilder: (context, index){
return Text(punkteanzahl_teamEins[index].toString());
}
),
new Row()
],
),
new Column(
children: <Widget>[
new IconButton(
icon: Icon(Icons.exposure_plus_2),
onPressed: () => punkte_hinzuzaehlen(2, 2)
)],
)
],
)
),
);
}
void punkte_hinzuzaehlen(int team, int nummer){
if (team == 1){
//Team 1 bekommt die Punkte
print("Team 1 gets points");
}
else if(team == 2){
//Team 2 bekommt die Punkte
print("Team 2 gets points");
}
}
}
And this is the error message:
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (26028): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter (26028): The getter 'length' was called on null.
I/flutter (26028): Receiver: null
I/flutter (26028): Tried calling: length
After the fix, I got another error:
══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (26028): The following assertion was thrown during performResize():
I/flutter (26028): Vertical viewport was given unbounded width.
I/flutter (26028): Viewports expand in the cross axis to fill their container and constrain their children to match
I/flutter (26028): their extent in the cross axis. In this case, a vertical viewport was given an unlimited amount of
I/flutter (26028): horizontal space in which to expand.

punkteanzahl_teamEins is only declared. But not initialized. So it is throwing null error.
You should assign value to punkteanzahl_teamEins as
List<int> punkteanzahl_teamEins = [1,4,5,7];
or pass data from parent as requirement.

We spend lost's of time to resolve issue finally we got a solution is: Please check you pubspec.yaml and remove extra '-' in case of assets file and also please follow the structure of that like spacing and all that.
We are must sure that issue only in pubspec.yaml file

First one check spieler_namen is null or not.If it is null then use below code i hope this will solve your problem.....
if(spieler_namen == null){
new Container(width: 10.0,height: 10.0,);
}else{
your requirement .......
}

In our case, we got this error when Internet Connection is off after calling webservice.

Initialize your list, and run hot restart (press R).
It works correctly.

If you called api in your project. check your device network connection. try to re start your simulator. that will fix this error.

I fix this by revisiting this section in pubspec.yaml
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
Ensure your spacing, hyphens and filenames are correct.
Note: You do not need to list every image file; instead, you can just list their directory:
assets:
- images/

Related

How do I run the debugger in Android Studio in order to figure out this error?

When my app goes from one screen to the other, there is a very brief moment where the app shows the red screen with some error about a Null in yellow letters and then it disappears. Is there a way to run Android Studio in a "step-by-step" way so that I can see exactly what variable is Null and when it gets filled?
======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building ChatScreen(dirty, dependencies: [_InheritedStateContainer], state: _ChatScreenState#93181):
type 'Null' is not a subtype of type 'String'
Code:
return GestureDetector(
child: groupWidget(groupName, groupID),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ChatScreen(groupID: groupID,)), //The error is on this line
);
}
);
Update:
Ok so I found a way to start the debugger, set a breakpoint where the error was pointing to, and then stepped through each line using F7. It looks like the problem isn't actually on this starting screen, it's on the landing screen (which is strange because the console points to a line on the starting screen). The problem is with the variable groupName in the code below. For some reason it starts as Null and then gets filled. My intention here is that when the user loads this screen, the name of the group is retrieved from Firestore and then displayed at the top. Why would this variable be null if I'm initializing it in initState()?
class _ChatScreenState extends State<ChatScreen> {
final database = Database();
var groupMembersList = [];
var groupName;
FirebaseFirestore firestore = FirebaseFirestore.instance;
late final Stream<QuerySnapshot> groupMembersStream = firestore.collection('groups').doc(widget.groupID).collection('GroupMembers').snapshots();
#override
void initState() {
super.initState();
initialize();
activateGroupMembersListener();
}
void initialize() async {
var tempGroupName = await database.getGroupName(widget.groupID);
setState(() {
groupName = tempGroupName;
});
}
#override
Widget build(BuildContext context) {
final container = StateContainer.of(context);
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
color: Colors.white,
onPressed: () {
container.stopMyApp();
Navigator.pop(context);
},
),
title: Text(
groupName, //ERROR IS HERE, THIS VARIABLE IS NULL
),
//...rest of code//
)
)
}
}
Adding a breakpoint where you initialized groupName should help, also at MaterialPageRoute line.

Null check operator used on a null value for flutter [duplicate]

This question already has answers here:
Null check operator used on a null value
(12 answers)
Closed last year.
So I am switching a project to flutter null safety but i am getting Null check operator used on a null value error i tried looking into other similar issue tried but its not working for me the complete error is as following
The following _CastError was thrown building HomeBanner(dirty, dependencies: [MediaQuery, _InheritedProviderScope<HomeViewModel>], state: _HomeBannerState#2de56):
Null check operator used on a null value
The relevant error-causing widget was:
HomeBanner file:///D:/fabricoMAt/lib/ui/views/home_screen.dart:26:17
When the exception was thrown, this was the stack:
#0 HomeViewModel.initData (package:knoty/business_logic/view_models/home_viewmodel.dart:25:33)
#1 _HomeBannerState._getImageSliders (package:knoty/ui/widgets/home_banner.dart:30:18)
#2 _HomeBannerState.build (package:knoty/ui/widgets/home_banner.dart:20:23)
#3 StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
...
====================================================================================================
======== Exception caught by widgets library =======================================================
Null check operator used on a null value
The relevant error-causing widget was:
WhomeServices file:///D:/fabricoMAt/lib/ui/views/home_screen.dart:43:17
And so onn this is coming at multiple place and i am not getting any idea how to fix this.
HomeViewModel model = Provider.of<HomeViewModel>(context);
Size screenSize = MediaQuery.of(context).size;
return model.initData == null //home_banner line 30
? [1, 2, 3, 4]
.map(
(item) => Shimmer.fromColors(
child: Container(
margin: EdgeInsets.only(right: 8),
width: screenSize.width * .7,
height: screenSize.width * .35,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(8.0),
),
color: Colors.black,
),
),
baseColor: Colors.grey.shade300,
highlightColor: Colors.grey.shade100,
),
)
.toList()
the other mentioned line
Init? _initData;
City get selectedCity {
return _initData!.cities
.firstWhere((element) => element.id == _initData!.selectedCityId);
}
Init get initData => _initData!;// home_viewmodel.dart 25
In home_banner at line 30, you are using initData method which returns a not nullable value.
So make a nullable return type of initData and remove ! from _initData.
Init? get initData => _initData;// home_viewmodel.dart 25
And if you are using get selectedCity in your code without checking the null value of _initData, this may cause an error in your code,
So add a null check in this method also.
City get selectedCity {
City? city = _initData?.cities
.firstWhere((element) => element.id == _initData?.selectedCityId);
if(city==null){
return City();// return default city
}else{
return city;
}
}

cant get subcollection in firebase firestore

i cant get subcollection that i created before. i am able to create subcollection named "sinav_gorselleri" after i pressed this RaisedButton and going to SinavOlusturPage with this code:
RaisedButton(
color: Colors.blue,
child: Text("Sınav oluştur"),
onPressed: () async{
final newDoc = await FirebaseFirestore.instance.collection("ders_sinavlari_olusturulanlar")
.add({"baslik": "4oluşturulanSınav2", "gorsel": "gorsel", "konu": "", "ogretmen": "ömer kalfa",
"sira": 3, "tarih": ""});
final idnewDoc = newDoc.id;
debugPrint(idnewDoc);
final newDoc_newCol = await newDoc.collection("sinav_gorselleri")
.add({"gorsel": "https://firebasestorage.googleapis.com/v0/b/sbycpaldemo.appspot.com/o/ders_notlari_gorseller%2Fyeni?alt=media&token=4af59ada-4a8b-45cc-86ef-2f691a5baf62"});
final idnewCol = await newDoc_newCol.id;
debugPrint(idnewCol);
Navigator.of(context,rootNavigator: true).pop('dialog');
Navigator.push(context, MaterialPageRoute(builder: (context)=> SinavOlusturPage(idnewDoc: idnewDoc,)));
}),
and in SinavOlusturPage i am expecting to get first doc in subcollection named "sinav_gorselleri" but cant get it with this code:
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class SinavOlusturPage extends StatefulWidget{
final idnewDoc;
const SinavOlusturPage({Key key, this.idnewDoc}) : super(key: key);
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return SinavOlusturPageState(this.idnewDoc);
}
}
class SinavOlusturPageState extends State {
final idnewDoc;
SinavOlusturPageState(this.idnewDoc);
File _imageSelected;
final _formKey = GlobalKey<FormState>();
final _scaffoldKey = GlobalKey<ScaffoldState>();
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(key: _scaffoldKey,
appBar: AppBar(
title: Text("SINAV OLUŞTURMA SAYFASI"),
),
body: ListView(
children: [
Center(
child: Text("..."),
StreamBuilder(
stream: FirebaseFirestore.instance.collection("ders_sinavlari_olusturulanlar/$idnewDoc/sinav_gorselleri").snapshots(),
builder: (context, snapshot){
final querySnapshot = snapshot.data();
return GridView.builder(
itemCount: 3,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
mainAxisSpacing: 10, crossAxisCount: 2,),
itemBuilder: (context, index){
final mapOlusturulan = querySnapshot.docs[index].data();
final idOlusturulan = querySnapshot.docs[index].id;
return GridTile(
child: Center(
child: Image.network(mapOlusturulan["gorsel"])),
);
});
})
],
),
);
}
}
i did tried
FirebaseFirestore.instance.collection("ders_sinavlari_olusturulanlar").doc(idnewDoc) .collection("sinav_gorselleri").snapshots(), also but cant do it. here is my error that i get all the time:
Performing hot reload...
Syncing files to device SNE LX1...
════════ Exception caught by image resource service ════════════════════════════════════════════════
The following ArgumentError was thrown resolving an image codec:
Invalid argument(s): No host specified in URI file:///gorsel
When the exception was thrown, this was the stack:
#0 _HttpClient._openUrl (dart:_http/http_impl.dart:2407:9)
#1 _HttpClient.getUrl (dart:_http/http_impl.dart:2328:48)
#2 NetworkImage._loadAsync (package:flutter/src/painting/_network_image_io.dart:89:59)
#3 NetworkImage.load (package:flutter/src/painting/_network_image_io.dart:50:14)
#4 ImageProvider.resolveStreamForKey.<anonymous closure> (package:flutter/src/painting/image_provider.dart:504:13)
...
Image provider: NetworkImage("gorsel", scale: 1.0)
Image key: NetworkImage("gorsel", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The method 'call' was called on null.
Receiver: null
Tried calling: call()
The relevant error-causing widget was:
StreamBuilder<QuerySnapshot> file:///C:/ornekler/sby_cpal_demo/lib/Dersler/SinavOlusturPage.dart:39:9
════════════════════════════════════════════════════════════════════════════════════════════════════
Reloaded 22 of 694 libraries in 3.748ms.
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#41144):
Class 'QuerySnapshot' has no instance method 'call'.
Receiver: Instance of 'QuerySnapshot'
Tried calling: call()
The relevant error-causing widget was:
StreamBuilder<QuerySnapshot> file:///C:/ornekler/sby_cpal_demo/lib/Dersler/SinavOlusturPage.dart:39:9
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 SinavOlusturPageState.build.<anonymous closure> (package:sby_cpal_demo/Dersler/SinavOlusturPage.dart:42:50)
#2 StreamBuilder.build (package:flutter/src/widgets/async.dart:525:81)
#3 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:129:48)
#4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by image resource service ════════════════════════════════════════════════
Invalid argument(s): No host specified in URI file:///gorsel
════════════════════════════════════════════════════════════════════════════════════════════════════
"gorsel" is my unique field key of subcollection document. this error realy makes me tired but really need to use subcollections in my app.
i didnt solved this with codings i just removed all the codes, pages and stuffs recorded to firebase firestore and rewrite them all step by step. i guess i get the reason of the error. it was about navigation time. after i pressed the button named Sinav Oluştur i was expecting the creation of the subcollection named "soru_gorselleri" of new document firstly and then navigation to SinavOlusturPage but all of these were happennig reversely so the Page was returning null. after i did all of them step by step with different RisedButtons , all of errors gone and happy end.

How to solve Flutter drawer showing Vertical viewport was given unbounded height

To be mentioned I'm new to both Flutter and Stackoverflow.
In my News reader app I have added a side drawer which pulls the news categories from an API using FutureBuilder. There is a DrawerHeader that contains the category named Popular News which is not fetched from the API, that is static.
Each time I'm opening the API, the Popular News category shows up and works fine but other categories do not show up rather in the console it shows an error like below.
I/flutter ( 4486): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4486): The following assertion was thrown during performResize():
I/flutter ( 4486): Vertical viewport was given unbounded height.
I/flutter ( 4486): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter ( 4486): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter ( 4486): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter ( 4486): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter ( 4486): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter ( 4486): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter ( 4486): the height of the viewport to the sum of the heights of its children.
My codes are given below
The widget that returns the Drawer
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return SizedBox(
width: SizeConfig.safeBlockHorizontal*50,
child: Theme(
data: Theme.of(context).copyWith(canvasColor: const Color(0xFF2b4849)),
child: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: ListTile(
title: Text(
"Popular News",
style: TextStyle(
color: Colors.white,
fontSize: 25
),
),
onTap: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => MostPopularNewsfeed(),
)
);
},
),
),
FutureBuilder(
future: category,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.data == null) {
return Container(
child: Center(
child: Text(
"Loading",
style: TextStyle(
color: Colors.white
),
),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return _getDrawer(snapshot, index);
},
);
}
},
),
],
),
),
),
);
}
initState() : This category is a Future<List>
void initState() {
super.initState();
setState(() {
category = fetchCategory();
});
}
fetchCategory() : This one fetches the categories from the API.
Future<List<Category>> fetchCategory() async {
//try {
String url = "https://tbsnews.net/json/category/news/list";
dio.interceptors.add(DioCacheManager(CacheConfig(baseUrl: url)).interceptor);
Response response = await Dio().get(url);
print(response);
List<Category> categoryList = [];
final Future<Database> dbFuture = categoryDatabaseHelper.initDb();
if(response.statusCode == 200) {
var decode = response.data;
print(decode);
for (var c in decode) {
Category category = Category(c['tid'], c['name']);
await categoryDatabaseHelper.insertCategory(category);
categoryList.add(category);
}
return categoryList;
//categoryDatabaseHelper.insertCategory(categoryList);
} else {
throw Exception("Failed to fetch category");
}
}
What I have tried so far
I have tried putting the DrawerHeader and FutureBuilder inside an Expanded widget instead of ListView. Did not work.
In the ListView I added shrinkWrap: true, also scrollDirection: Axis.vertical. That was of no use either.
Tried to put them inside a SizeBox and Column widgets also. That did not work either.
The above are what I found by searching the previous questions related to this issue in StackOverflow. Lastly, I'm posting a question myself.
To be noted, when I take away that DrawerHeader everything starts working fine, no trouble then anymore. But this DrawerHeader has to be there.
Thank you very much for your time and sincere help.
If the issue is only with the DrawerHeader try to wrap it with a SizedBox or a ConstrainedBox and give it a certain height and width.
The issue is that the DrawerHeader is not conststrained so the ListView while being built doesn't get to know its dimensions or constraints and throws this error.
This is my educated guess and let me know whether it worked or not.

flutter (Dart) Method 'tr' Called at null

I got this flutter app works with two languages. Display items in menus well but when I try to edit and route to edit page it comes this error,
(I use add and edit at the same page route but the parameters are different) When I try to add the route works well without any errors but when I try to edit the app start giving me a lot of errors at console and (Method called at null) and point at the String text I want to localize.
I used EasyLocalization widget.
here the error and code:
#override
Widget build(BuildContext context) {
var data = EasyLocalizationProvider.of(context).data;
return EasyLocalizationProvider (
data: data,
child: Scaffold (
appBar: AppBar (
title: Text(AppLocalizations.of(context).tr("Scan By Trip ID")),
centerTitle: true,
),
and here the error :
_EmployeeScreenState#a9074):
I/flutter (10733): The method 'tr' was called on null.
I/flutter (10733): Receiver: null
I/flutter (10733): Tried calling: tr("Scan By Trip ID")
you need to add this to your material app:
MaterialApp(
localizationsDelegates: [
// ... app-specific localization delegate[s] here
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
const Locale('en'), // English
const Locale('he'), // Hebrew
const Locale.fromSubtags(languageCode: 'zh'), // Chinese *See Advanced Locales below*
// ... other locales the app supports
],
// ...
)

Categories

Resources