Error "The method 'call' was called on null" for generating a list - list

In my application I use the following code:
#override
Widget build(BuildContext context) {
List<double> listMax = List.from(data_snap()['history']);
final listMaxreversed = List.from(listMax.reversed);
final list_one_week = listMaxreversed.take(
data_snap()['history']['1w']);
final list_one_week_list = List.from(list_one_week);
final list_one_week_list_rev = List.from(list_one_week_list.reversed);
List<FlSpot> spots_one_week =
list_one_week_list_rev
.asMap()
.entries
.map((e) {
return FlSpot(e.key.toDouble(), e.value);
}).toList();
print(spots_one_week);
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.lightGreen),
backgroundColor: Colors.grey[100],
title: const Text('Details', style:
TextStyle(color: Colors.lightGreen)),
),
body: Padding(
//some code here...
Row(
children: [ _loading ? CircularProgressIndicator():
new Container(
child:
LineChart(
LineChartData(
lineTouchData: LineTouchData(enabled: true),
gridData: FlGridData(
show: false,
drawHorizontalLine: false,
drawVerticalLine: false,
getDrawingVerticalLine: (value) {
return FlLine(
color: Colors.black,
strokeWidth: 1,
);
},
),
lineBarsData: [
LineChartBarData(
spots: spots_one_week, //inserts the spots here
A brief moment I get the following error on my phone. After this moment the chart is displayed correctly.
The method 'call' was called on null.
Receiver: null
Tried calling: call()
I think I have to include something like an async task. The error occurs directly when I define listMax. How can I solve this?

Related

Flutter property values of a Map all treated as strings

I have a list like this a = [{'one': 'one', 'two': null, 'three': [{'four': 'four'}]}]
I send it to a function to use it in a post request which in the body should receive a Map, so what I did was this to a[0], the problem is that I get this error The getter 'length' was called on null
I start to review and it treats all the property values as if they were Strings, even the nested list 'three': [{'four': 'four'}], I have tried to send the post in this way http.post (url, body: (recurrence [0] as Map)) but it has not worked, it always gives me the same error, even if in the body I put the properties by hand in the body: {'new property': a [0] [' tres']}, how should one act to solve this problem? Thank you very much for your help
Code:
void _ordersGet() async {
await http.get(url).then((value) {
setState(() {
orders = jsonDecode(value.body);
}
}
orders is sent to a new widget: orderList(orders)
orderList is a listView
ListView.builder(
shrinkWrap: true,
primary: false,
itemCount: orders.length,
itemBuilder: (orders, index) {
return return Card(
elevation: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(orders[index]['facts']),
SizedBox(
width: 4,
),
Text('Cantidad : '),
Text(orders[index]['ITEMS'][0]['jeans']),
SizedBox(
width: 4,
),
IconButton(
onPressed: () => _reorderData(context, orders[index]),
icon: Icon(
Icons.replay_outlined,
color: Theme.of(context).accentColor,
)),
],
),
);
},
);
_reorderData is a function that make a get request, the info in shipped to ReorderModal
ReorderModal it only shows the information and has a button
void _reorderData(BuildContext ctx, order) async {
var data;
var url = 'serverAddress/${order['facts']}';
await http.get(url).then((value) {
data = jsonDecode(value.body);
data[0]['CORPORATION'] = order['corporation'];
showModalBottomSheet(
context: ctx,
builder: (_) {
return ReorderModal(data);
});
}).catchError((onError) {});
}
class ReorderModal extends StatelessWidget {
final List data;
ReorderModal(this.data);
void orderSend(orderInfo) async {
var url = 'serverAddress';
await http.post(url, body: orderInfo[0]).then((value) {
print(jsonDecode(value.body));
}).catchError((onError) {
print(onError);
});
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10),
child: Column(children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Column(
children: [
ElevatedButton(
onPressed: () {
orderSend(data);
//print(data);
},
child: Text('ONE Click'))
]),
);
}
}
when i press the ONE Click button execute the function orderSend, orderSend make a post request and the problem described above
This is the simplified code, I know it must be something very simple, but it is giving me a lot of work to solve

Unable to use the .map function in Flutter

So I am following along a book about Flutter App Development where I was tasked to implement a ToDoMenuItem class and create a list in it.
class TodoMenuItem {
final String title;
final Icon icon;
TodoMenuItem({this.title, this.icon});
List<TodoMenuItem> foodMenuList = [
TodoMenuItem(title: 'Fast Food', icon: Icon(Icons.fastfood)),
TodoMenuItem(title: 'Remind Me', icon: Icon(Icons.add_alarm)),
TodoMenuItem(title: 'Flight', icon: Icon(Icons.flight)),
TodoMenuItem(title: 'Music', icon: Icon(Icons.audiotrack)),
];
}
Then I was tasked to map it to a PopUpMenuButtonWidget using an itemBuilder. Here is the class I wrote for it.
class PopupMenuButtonWidget extends StatelessWidget
implements PreferredSizeWidget {
const PopupMenuButtonWidget({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
color: Colors.lightGreen.shade100,
height: preferredSize.height,
width: double.infinity,
child: Center(
child: PopupMenuButton<TodoMenuItem>(
icon: Icon(Icons.view_list),
onSelected: ((valueSelected) {
print('valueSelected: ${valueSelected.title}');
}),
itemBuilder: (BuildContext context) {
return foodMenuList.map((TodoMenuItem todoMenuItem) {
return PopupMenuItem<TodoMenuItem>(
value: todoMenuItem,
child: Row(
children: <Widget>[
Icon(todoMenuItem.icon.icon),
Padding(
padding: EdgeInsets.all(8.0),
),
Text(todoMenuItem.title),
],
),
);
}).toList();
},
),
),
);
}
#override // implement preferredSize
Size get preferredSize => Size.fromHeight(75.0);
}
However, it returns an error at this line.
return foodMenuList.map((TodoMenuItem todoMenuItem) {
And the error says
Undefined name 'foodMenuList'.
Try correcting the name to one that is defined, or defining the name.
How can I 'map' the foodMenuList list to the widget?
Your foodMenuList is declared in todoMenuItem class, while you try to refer to it like it would be a part of PopupMenuButtonWidget (you are doing this.foodMenuList in context of PopupMenuButtonModget)
You could create instantiate an instance of TodoMenuList in PopupMenuButtonWidget and then use it.
final TodoMenuItem _todoMenu = TodoMenuItem();
Widget build(BuildContext context) {
...
// Someplace where you need to use the list
_todoMenu.foodMenuList
...
}

Is there a way to test a Dart program as unchecked (production) mode?

Some of my classes uses assert() to make development easier.
The problem is that those asserts are ignored in production mode, so I need a way to write tests for times when those assertions fail (when they throw assertionErrors).
main() {
// test if the assertion is being throw correctly
test('null emailStr assertion', () {
expect(() => Email(emailStr: null), throwsAssertionError);
});
// here I want to test how it would behave in prod mode
// when the asserts are ignored.
// This way it'll just throw an assertion error
test('null emailStr emailStr value', () {
final Email email = Email(emailStr: null);
expect(email.isValid, false);
});
}
I wonder if there's something like this to run tests as if we were in production mode:
setUp(isCheckedMode = false)
I found in google that the only way to message someone in stack is to write a comment in his question.
However, my code of another class (MessageBubble) is:
class MessageBubble extends StatelessWidget {
final String messsage;
final userID;
final bool isMe;
final Key key;
MessageBubble(this.messsage,this.userID, this.isMe,this.key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: isMe? MainAxisAlignment.start: MainAxisAlignment.end,
children: [
Container(
decoration: BoxDecoration(
color: isMe? Colors.grey[300]: nave,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
bottomLeft: !isMe ? Radius.circular(12) : Radius.circular(0),
bottomRight: isMe ? Radius.circular(12) : Radius.circular(0),
),
),
width: 140,
padding: EdgeInsets.symmetric(vertical: 10,horizontal: 16),
margin: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
child: Column(
children: [
Column(
children: [
FutureBuilder(
future: FirebaseFirestore.instance.collection('users').doc(userID).get(),
builder: (context, snapshot) {
if(snapshot.connectionState== ConnectionState.waiting){
return Text('جاري التحميل...');}
return Text(snapshot.data['username'], style: TextStyle(fontWeight: FontWeight.bold),);
}
),
],
),
Text(messsage, style: TextStyle(color: isMe? white : Colors.black,),),
],
) ,
),
],
);
}
}
my code in main:
home:
StreamBuilder(stream: FirebaseAuth.instance.authStateChanges(), builder: (ctx, userSnapshot) {
if (userSnapshot.hasData) {
return ChatPage();
}
return FirstPage();
}),

Flutter return Firestore array values to a List

I am using Flutter table calendar plugin to make a calendar. In order to put events into the calendar, I have to add data to _events map. I want to get the data from Firestore document, and put the data into _events map. However, I don't know how to do it. I search everywhere but I can't get an answer.
This is my code
class _MemberEventsState extends State<MemberEvents>
with TickerProviderStateMixin {
Map<DateTime, List> _events;
List _selectedEvents;
AnimationController _animationController;
CalendarController _calendarController;
List<String> list = List();
#override
void initState() {
super.initState();
final _selectedDay = DateTime.now();
Firestore.instance
.collection('events')
.document('2019-07-30')
.get()
.then((DocumentSnapshot ds) {
list = List.from(ds['title']);
});
_events = {DateTime.parse("2019-08-01"): list};
_selectedEvents = _events[_selectedDay] ?? [];
_calendarController = CalendarController();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
_animationController.forward();
}
#override
void dispose() {
_animationController.dispose();
_calendarController.dispose();
super.dispose();
}
void _onDaySelected(DateTime day, List events) {
print('CALLBACK: _onDaySelected');
setState(() {
_selectedEvents = events;
});
}
void _onVisibleDaysChanged(
DateTime first, DateTime last, CalendarFormat format) {
print('CALLBACK: _onVisibleDaysChanged');
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
_buildTableCalendar(),
const SizedBox(height: 8.0),
const SizedBox(height: 8.0),
Expanded(child: _buildEventList()),
],
),
);
}
Widget _buildTableCalendar() {
return TableCalendar(
calendarController: _calendarController,
events: _events,
startingDayOfWeek: StartingDayOfWeek.sunday,
calendarStyle: CalendarStyle(
selectedColor: Colors.deepOrange[400],
todayColor: Colors.blueAccent[200],
markersColor: Colors.brown[700],
outsideDaysVisible: false,
),
headerStyle: HeaderStyle(
formatButtonTextStyle:
TextStyle().copyWith(color: Colors.white, fontSize: 15.0),
formatButtonDecoration: BoxDecoration(
color: Colors.deepOrange[400],
borderRadius: BorderRadius.circular(16.0),
),
),
onDaySelected: _onDaySelected,
onVisibleDaysChanged: _onVisibleDaysChanged,
);
}
Widget _buildEventList() {
return ListView(
children: _selectedEvents
.map((event) => Container(
decoration: BoxDecoration(
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin:
const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
child: ListTile(
title: Text(event.toString()),
),
))
.toList(),
);
}
}
So in the first step to achieve my goal, I made a document named 2019-07-30, then I made an array in it named title. Then I tried to get the values in the array to a List named list. However, list returned null.
I don't know where I went wrong.
I am new to Flutter, so the question might seem stupid.
Also, I am new to stackoverflow, so if I did any steps wrong on describing the question, please tell me so I can fix it.

error: The named parameter 'children' isn't defined, while using a ListView

I am using Firebase realtime database to retrieve information and then present it in a scrollable DataTable.
To make the DataTable scrollable, I wrapped it up in a ListView, as per the comment of this post:
DataTable - make scrollable, set background colour and fix/freeze header row and first column
This is my code:
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'cprdata.dart';
import 'dart:convert';
class CprAnalysis extends StatefulWidget {
#override
CPRState createState() => CPRState();
}
class CPRState extends State<CprAnalysis> {
///var cpr = UpdateData.getData();
List<FilterData> acData;
List<FilterData> getData() {
var cpr = <FilterData>[];
DatabaseReference cprData = FirebaseDatabase.instance.reference();
cprData.reference().once().then((DataSnapshot snap) {
var d = snap.value;
final jsonE = json.encode(d);
final jsonResponse = json.decode(jsonE);
MyDataList zz = new MyDataList.fromJson(jsonResponse);
zz.myList.forEach((data) {
cpr.add(FilterData(sYMBOL: data.SYMBOL, fORECAST: data.FORECAST));
}
);
},
);
print(cpr);
return cpr;
}
#override
void initState() {
super.initState();
acData = getData();
}
Widget bodydata() => Expanded(
child: ListView(
///shrinkWrap: true,
padding: const EdgeInsets.all(8.0),
childern: <Widget>[
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
columns: <DataColumn>[
DataColumn(
label: Text("Symbol"),
numeric: false,
),
DataColumn(
label: Text("Forecast"),
numeric: false,
),
],
rows: acData.map((data) =>
DataRow(
cells: [
DataCell(
Text(data.sYMBOL),
showEditIcon: false,
placeholder: false,
),
DataCell(
Text(data.fORECAST),
showEditIcon: false,
placeholder: false,
)
],
),
)
.toList()
),
),
]
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("CPR Analysis"),
),
body: Container(
child: bodydata(),
),
);
}
}
class FilterData {
String sYMBOL, fORECAST;
FilterData({
this.sYMBOL,
this.fORECAST});
}
Expected output: Scrollable DataTable.
Actual output: error: The named parameter 'childern' isn't defined under ListView()
You misspelled children as childern in your code.
Make your ListView code as -
ListView(
children: <Widget> [
//Your remaining code
]
),