Related
I am trying to display a list in flutter. The list has 2 parts, one is the parent name and under that, I have the subcategories. I am fetching the data using an API and trying to create checkboxes using the fetched data. I am unable to understand how to display the lists properly. As posted in the image, the main header is being displayed equal to the number of categories it holds. I want to display a single header and the subcategories under it. Kindly Help.
Function for List Builder
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Column(
children: [
ExpansionTile(
title: Text(snapshot.data[index].p_cat_name),
children: [
ListTile(
title: Text(snapshot.data[index].c_cat_name),
leading: Checkbox(
value: CategoriesDsiplay.userStatus[index] =
!CategoriesDsiplay.userStatus[index],
onChanged: (bool? val) {
setState(() {
CategoriesDsiplay.userStatus[index] =
!CategoriesDsiplay.userStatus[index];
});
},
),
),
],
),
],
);
},
);
Function for adding data to the list
Future<List<CategoryFiltersList>> getCategoryList() async {
var url = Uri.parse(
urlhere );
final headers = {'Content-Type': 'application/x-www-form-urlencoded'};
Map<String, dynamic> body = {
'st_search': '',
};
final encoding = Encoding.getByName('utf-8');
Response response = await post(
url,
headers: headers,
body: body,
encoding: encoding,
);
var schemeBody = response.body;
var jsonData = json.decode(schemeBody);
List<CategoryFiltersList> categoryFiltersLists = [];
for (var sch in jsonData) {
// String credentials = sch['isin'];
// Codec<String, String> stringToBase64 = utf8.fuse(base64);
// Body.encoded =
// stringToBase64.encode(credentials); // dXNlcm5hbWU6cGFzc3dvcmQ=
CategoryFiltersList categoryFiltersList = CategoryFiltersList(
sch['mf_cat_id'],
sch['p_cat_name'],
sch['c_cat_name'],
);
if (sch['mf_cat_id'] != null) {}
categoryFiltersLists.add(categoryFiltersList);
CategoriesDsiplay.userStatus.add(false);
}
return categoryFiltersLists;
}
Json Data:
flutter: [{mf_cat_id: 6, p_cat_name: EQUITY, c_cat_name: Value_Fund}, {mf_cat_id: 7, p_cat_name: EQUITY, c_cat_name: Large_Cap}, {mf_cat_id: 8, p_cat_name: EQUITY, c_cat_name: Large_&_Midcap}, {mf_cat_id: 9, p_cat_name: EQUITY, c_cat_name: Multicap}, {mf_cat_id: 10, p_cat_name: EQUITY, c_cat_name: Midcap}, {mf_cat_id: 11, p_cat_name: EQUITY, c_cat_name: Small_Cap}, {mf_cat_id: 13, p_cat_name: EQUITY, c_cat_name: Focussed_Fund}, {mf_cat_id: 14, p_cat_name: EQUITY, c_cat_name: Dividend_Yield_Fund}, {mf_cat_id: 15, p_cat_name: HYBRID, c_cat_name: Arbitrage_Fund}, {mf_cat_id: 16, p_cat_name: HYBRID, c_cat_name: Conservative_Hybrid_Fund}, {mf_cat_id: 17, p_cat_name: HYBRID, c_cat_name: Equity_Savings_Fund}, {mf_cat_id: 18, p_cat_name: HYBRID, c_cat_name: Dynamic_Asset_Allocation_Fund}, {mf_cat_id: 19, p_cat_name: HYBRID, c_cat_name: Balanced_Advantage_Fund}, {mf_cat_id: 20, p_cat_name: HYBRID, c_cat_name: Aggressive_Hybrid_Fund}, {mf_cat_id: 21, p_cat_name: HYBRID, c_cat_name: Multi_Assest_Allocatio<…>
Your ListView.builder builds this for every one of your responses:
Column(
children: [
ExpansionTile(
title: Text(snapshot.data[index].p_cat_name),
children: [
ListTile(
title: Text(snapshot.data[index].c_cat_name),
leading: Checkbox(
value: CategoriesDsiplay.userStatus[index] =
!CategoriesDsiplay.userStatus[index],
onChanged: (bool? val) {
setState(() {
CategoriesDsiplay.userStatus[index] =
!CategoriesDsiplay.userStatus[index];
});
},
),
),
],
),
],
);
The problem with this is that your app builds a new ExpansionTile for every element in your response list.
To fix this you have to find out which and how many 'p_cat_name's your response has and build an ExpansionTile for every p_cat_name. As a child it should have another ListView.builder that builds a ListTile for every element from response array that has the same p_cat_name as the parent (you can do this with if statement checks).
I want to improve the following code snippet by removing the hard coded number 5 (the number of elements in the list). How to do so?
child: TabBar(
tabs: <Widget>[
...List.generate(
5,
(i) => Tab(
child: Text([
'Text',
'Icons',
'Images',
'Simple Form',
'Proper Form'
][i]),
),
),
],
),
Something like
tabs:
'Text/Icons/Images/Simple Form/Proper Form'.split('/').
map((e) => Tab(child: Text(e)).toList();
It's simple.
Define your list of Strings as the main source for your interface, iterate over it and create the Tab widgets.
TabBar(
tabs: [
'Text',
'Icons',
'Images',
'Simple Form',
'Proper Form'
].map(
(tabName) => Tab(child: Text(tabName))
).toList()
)
My flutter code is,
this code is written via exporting Adobe XD file and adding with the default main.dart
code is generated through Adobe XD and putted to VS code with exporting.
It is showing this error in debug console
Please help with this code.
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:adobe_xd/blend_mask.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xffffffff),
body: Stack(
children: <Widget>[
Transform.translate(
offset: Offset(-6.0, -9.0),
child: SvgPicture.string(
_svg_hscwvz,
allowDrawingOutsideViewBox: true,
),
),
Transform.translate(
offset: Offset(-48.0, 65.0),
child: SizedBox(
width: 424.0,
height: 266.0,
child: Text.rich(
TextSpan(
style: TextStyle(
fontFamily: 'Google Sans',
fontSize: 30,
color: const Color(0xff707070),
),
children: [
TextSpan(
text: ' ',
),
TextSpan(
text: 'DO YOU KNOW?\n',
style: TextStyle(
fontWeight: FontWeight.w700,
),
),
TextSpan(
text:
'\n YOU CAN BETTER THE\n PERFORMANCE OF YOUR\n EARPHONE BY 63%.\n\n JUST BY USING THIS APP',
),
],
),
textAlign: TextAlign.center,
),
),
),
Transform.translate(
offset: Offset(18.0, 433.0),
child: SizedBox(
width: 14.0,
child: Text(
'',
style: TextStyle(
fontFamily: 'Google Sans',
fontSize: 30,
color: const Color(0xff707070),
),
textAlign: TextAlign.center,
),
),
),
Transform.translate(
offset: Offset(103.0, 402.0),
child: SizedBox(
width: 206.0,
height: 114.0,
child: Text(
'JUST FOLLOW \nTHESE SIMPLE \nSTEPS …',
style: TextStyle(
fontFamily: 'Google Sans',
fontSize: 30,
color: const Color(0xff707070),
),
textAlign: TextAlign.center,
),
),
),
// Adobe XD layer: 'graphs' (group)
BlendMask(
blendMode: BlendMode.multiply,
opacity: 1,
region: Offset(-64.0, 554.9) & Size(495.0, 149.2),
child: Stack(
children: <Widget>[
Transform.translate(
offset: Offset(-64.0, 554.86),
child: SvgPicture.string(
_svg_6t608q,
allowDrawingOutsideViewBox: true,
),
),
],
),
),
],
),
);
return MaterialApp(
title: 'Ehtasham app',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
const String _svg_hscwvz =
'<svg viewBox="-6.0 -9.0 424.0 866.0" ><defs><linearGradient id="gradient" x1="0.5" y1="0.2911" x2="0.5" y2="1.0"><stop offset="0.0" stop-color="#ff4fffb7" /><stop offset="1.0" stop-color="#ff5173fb" /><stop offset="1.0" stop-color="#ff76998b" /><stop offset="1.0" stop-color="#ff808080" /></linearGradient></defs><path transform="translate(-6.0, -9.0)" d="M 0 0 L 424 0 L 424 866 L 0 866 L 0 0 Z" fill="url(#gradient)" stroke="#090909" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_6t608q =
'<svg viewBox="-64.0 554.9 495.0 149.2" ><path transform="translate(-1146.85, -6457.22)" d="M 1533.19384765625 7060.17333984375 C 1464.86669921875 7058.81982421875 1463.255249023438 7082.07958984375 1418.307250976562 7082.07958984375 C 1373.359252929688 7082.07958984375 1346.678833007812 7047.59765625 1300.068969726562 7047.59765625 C 1253.459106445312 7047.59765625 1239.491333007812 7052.82373046875 1189.326782226562 7052.82373046875 C 1139.162231445312 7052.82373046875 1082.85009765625 7012.07958984375 1082.85009765625 7012.07958984375 C 1082.85009765625 7012.07958984375 1082.85009765625 7161.27685546875 1082.85009765625 7161.27685546875 C 1082.85009765625 7161.27685546875 1533.19384765625 7161.27685546875 1533.19384765625 7161.27685546875 C 1533.19384765625 7161.27685546875 1533.19384765625 7060.17333984375 1533.19384765625 7060.17333984375 Z" fill="none" fill-opacity="0.05" stroke="#2699fb" stroke-width="10" stroke-opacity="0.05" stroke-miterlimit="4" stroke-linecap="butt" /><path transform="translate(-1150.85, -6434.0)" d="M 1533.19384765625 7062.5625 C 1464.86669921875 7061.75927734375 1470.591186523438 7037.07421875 1425.643188476562 7037.07421875 C 1380.695190429688 7037.07421875 1362.970458984375 7074.9140625 1295.2060546875 7074.9140625 C 1258.198974609375 7074.9140625 1227.359741210938 7037.07421875 1193.514282226562 7037.07421875 C 1159.668579101562 7037.07421875 1112.85009765625 7054.0546875 1112.85009765625 7054.0546875 C 1112.85009765625 7054.0546875 1112.85009765625 7109.0546875 1112.85009765625 7109.0546875 C 1112.85009765625 7109.0546875 1533.19384765625 7109.0546875 1533.19384765625 7109.0546875 C 1533.19384765625 7109.0546875 1533.19384765625 7062.5625 1533.19384765625 7062.5625 Z" fill="none" fill-opacity="0.2" stroke="#2699fb" stroke-width="5" stroke-opacity="0.2" stroke-miterlimit="4" stroke-linecap="butt" /><path transform="translate(-1181.85, -6419.0)" d="M 1142.850219726562 7049.0546875 C 1221.619995117188 7048.25146484375 1220.568115234375 7001.95703125 1272.385375976562 7001.95703125 C 1324.20263671875 7001.95703125 1339.0888671875 7071.9140625 1417.209594726562 7071.9140625 C 1472.696044921875 7071.9140625 1491.203125 7032.0546875 1530.221313476562 7032.0546875 C 1569.239501953125 7032.0546875 1612.850219726562 7049.0546875 1612.850219726562 7049.0546875 C 1612.850219726562 7049.0546875 1612.850219726562 7109.0546875 1612.850219726562 7109.0546875 C 1612.850219726562 7109.0546875 1142.850219726562 7109.0546875 1142.850219726562 7109.0546875 C 1142.850219726562 7109.0546875 1142.850219726562 7049.0546875 1142.850219726562 7049.0546875 Z" fill="none" fill-opacity="0.5" stroke="#2699fb" stroke-width="2" stroke-opacity="0.5" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
it is showing this error in debug console
please help with this code.
I/flutter (24258): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (24258): The following assertion was thrown building MyApp:
I/flutter (24258): MediaQuery.of() called with a context that does not contain a MediaQuery.
I/flutter (24258): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
I/flutter (24258): This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
I/flutter (24258): a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
I/flutter (24258): The context used was:
I/flutter (24258): Scaffold
I/flutter (24258):
I/flutter (24258): The relevant error-causing widget was:
I/flutter (24258): MyApp
lib\main.dart:6
I/flutter (24258):
I/flutter (24258): When the exception was thrown, this was the stack:
I/flutter (24258): ... Normal element mounting (7 frames)
I/flutter (24258): (elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
I/flutter (24258):
I/flutter (24258): ════════════════════════════════════════════════════════════════════════════════════════════════════
Code is generated through Adobe XD and putted to VS code with exporting.
You need to place the generated code inside Material app. I moved all the code to MyHomePage
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:adobe_xd/blend_mask.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Ehtasham app',
theme: ThemeData(
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xffffffff),
body: Stack(
children: <Widget>[
Transform.translate(
offset: Offset(-6.0, -9.0),
child: SvgPicture.string(
_svg_hscwvz,
allowDrawingOutsideViewBox: true,
),
),
Transform.translate(
offset: Offset(-48.0, 65.0),
child: SizedBox(
width: 424.0,
height: 266.0,
child: Text.rich(
TextSpan(
style: TextStyle(
fontFamily: 'Google Sans',
fontSize: 30,
color: const Color(0xff707070),
),
children: [
TextSpan(
text: ' ',
),
TextSpan(
text: 'DO YOU KNOW?\n',
style: TextStyle(
fontWeight: FontWeight.w700,
),
),
TextSpan(
text:
'\nYOU CAN BETTER THE\n PERFORMANCE OF YOUR\n EARPHONE BY 63%.\n\n JUST BY USING THIS APP',
),
],
),
textAlign: TextAlign.center,
),
),
),
Transform.translate(
offset: Offset(18.0, 433.0),
child: SizedBox(
width: 14.0,
child: Text(
'',
style: TextStyle(
fontFamily: 'Google Sans',
fontSize: 30,
color: const Color(0xff707070),
),
textAlign: TextAlign.center,
),
),
),
Transform.translate(
offset: Offset(103.0, 402.0),
child: SizedBox(
width: 206.0,
height: 114.0,
child: Text(
'JUST FOLLOW \nTHESE SIMPLE \nSTEPS …',
style: TextStyle(
fontFamily: 'Google Sans',
fontSize: 30,
color: const Color(0xff707070),
),
textAlign: TextAlign.center,
),
),
),
// Adobe XD layer: 'graphs' (group)
BlendMask(
blendMode: BlendMode.multiply,
opacity: 1,
region: Offset(-64.0, 554.9) & Size(495.0, 149.2),
child: Stack(
children: <Widget>[
Transform.translate(
offset: Offset(-64.0, 554.86),
child: SvgPicture.string(
_svg_6t608q,
allowDrawingOutsideViewBox: true,
),
),
],
),
),
],
),
);
}
}
const String _svg_hscwvz =
'<svg viewBox="-6.0 -9.0 424.0 866.0" ><defs><linearGradient id="gradient" x1="0.5" y1="0.2911" x2="0.5" y2="1.0"><stop offset="0.0" stop-color="#ff4fffb7" /><stop offset="1.0" stop-color="#ff5173fb" /><stop offset="1.0" stop-color="#ff76998b" /><stop offset="1.0" stop-color="#ff808080" /></linearGradient></defs><path transform="translate(-6.0, -9.0)" d="M 0 0 L 424 0 L 424 866 L 0 866 L 0 0 Z" fill="url(#gradient)" stroke="#090909" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_6t608q =
'<svg viewBox="-64.0 554.9 495.0 149.2" ><path transform="translate(-1146.85, -6457.22)" d="M 1533.19384765625 7060.17333984375 C 1464.86669921875 7058.81982421875 1463.255249023438 7082.07958984375 1418.307250976562 7082.07958984375 C 1373.359252929688 7082.07958984375 1346.678833007812 7047.59765625 1300.068969726562 7047.59765625 C 1253.459106445312 7047.59765625 1239.491333007812 7052.82373046875 1189.326782226562 7052.82373046875 C 1139.162231445312 7052.82373046875 1082.85009765625 7012.07958984375 1082.85009765625 7012.07958984375 C 1082.85009765625 7012.07958984375 1082.85009765625 7161.27685546875 1082.85009765625 7161.27685546875 C 1082.85009765625 7161.27685546875 1533.19384765625 7161.27685546875 1533.19384765625 7161.27685546875 C 1533.19384765625 7161.27685546875 1533.19384765625 7060.17333984375 1533.19384765625 7060.17333984375 Z" fill="none" fill-opacity="0.05" stroke="#2699fb" stroke-width="10" stroke-opacity="0.05" stroke-miterlimit="4" stroke-linecap="butt" /><path transform="translate(-1150.85, -6434.0)" d="M 1533.19384765625 7062.5625 C 1464.86669921875 7061.75927734375 1470.591186523438 7037.07421875 1425.643188476562 7037.07421875 C 1380.695190429688 7037.07421875 1362.970458984375 7074.9140625 1295.2060546875 7074.9140625 C 1258.198974609375 7074.9140625 1227.359741210938 7037.07421875 1193.514282226562 7037.07421875 C 1159.668579101562 7037.07421875 1112.85009765625 7054.0546875 1112.85009765625 7054.0546875 C 1112.85009765625 7054.0546875 1112.85009765625 7109.0546875 1112.85009765625 7109.0546875 C 1112.85009765625 7109.0546875 1533.19384765625 7109.0546875 1533.19384765625 7109.0546875 C 1533.19384765625 7109.0546875 1533.19384765625 7062.5625 1533.19384765625 7062.5625 Z" fill="none" fill-opacity="0.2" stroke="#2699fb" stroke-width="5" stroke-opacity="0.2" stroke-miterlimit="4" stroke-linecap="butt" /><path transform="translate(-1181.85, -6419.0)" d="M 1142.850219726562 7049.0546875 C 1221.619995117188 7048.25146484375 1220.568115234375 7001.95703125 1272.385375976562 7001.95703125 C 1324.20263671875 7001.95703125 1339.0888671875 7071.9140625 1417.209594726562 7071.9140625 C 1472.696044921875 7071.9140625 1491.203125 7032.0546875 1530.221313476562 7032.0546875 C 1569.239501953125 7032.0546875 1612.850219726562 7049.0546875 1612.850219726562 7049.0546875 C 1612.850219726562 7049.0546875 1612.850219726562 7109.0546875 1612.850219726562 7109.0546875 C 1612.850219726562 7109.0546875 1142.850219726562 7109.0546875 1142.850219726562 7109.0546875 C 1142.850219726562 7109.0546875 1142.850219726562 7049.0546875 1142.850219726562 7049.0546875 Z" fill="none" fill-opacity="0.5" stroke="#2699fb" stroke-width="2" stroke-opacity="0.5" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
I want to show a list of dates when a user selects days.
Container(
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
decoration: BoxDecoration(
border: Border.all(
width: 1.5,
color: Color(0xFF5c77e0),
style: BorderStyle.solid),
borderRadius: BorderRadius.circular(3)),
// dropdown below..
child: DropdownButton<String>(
isExpanded: true,
value: dropdownValue,
icon: Icon(Icons.keyboard_arrow_down),
iconSize: 30,
underline: SizedBox(),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>[
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList()),
),
Suppose the user selected 5 days. I want to display dates of the previous 5 days from the current date, e.g today's date is "21-03-2020". If the user selected 5 days the list should be like:
17-03-2020
18-03-2020
19-03-2020
20-03-2020
21-03-2020
How can I do this?
Assuming that your input is a numeric string value.
List<String> getDates(String dateCount){
List<String> dates=[];
var yourDateCountValue=int.parse(dateCount);
var dateToday=DateTime.now();
while(yourDateCountValue!=0){
//Print Full date
print(dateToday.subtract(Duration(days: yourDateCountValue-1)));
//Print Date Exactly of your format
print(dateToday.subtract(Duration(days: yourDateCountValue-1)).toIso8601String().substring(0,10));
//Add dates to the list being started from 5 days back.
dates.add(dateToday.subtract(Duration(days: yourDateCountValue-1)).toIso8601String().substring(0,10));
yourDateCountValue--;
}
return dates;
}
call your method as
getDates("5");
I have a set of films data/ratings, and I need to calculate the average of the ratings by film. It's like a sum on ratings groupby movieId in SQL.
Thank you very much for your help
I've tried to use aggregateBYKey, but I don't know how to use seqOp and CombOp functions. I'm new to PySpark.
here is a chunk of my RDD: [movieId, userId, rating, film]
[('1', '1', 4.0, 'Toy Story (1995)'),
('1', '5', 4.0, 'Toy Story (1995)'),
('1', '7', 4.5, 'Toy Story (1995)'),
('1', '15', 2.5, 'Toy Story (1995)'),
('1', '17', 4.5, 'Toy Story (1995)'),
('1', '18', 3.5, 'Toy Story (1995)'),
('1', '19', 4.0, 'Toy Story (1995)'),
('1', '21', 3.5, 'Toy Story (1995)'),
('1', '27', 3.0, 'Toy Story (1995)'),
('1', '31', 5.0, 'Toy Story (1995)'),
('1', '32', 3.0, 'Toy Story (1995)'),
('1', '33', 3.0, 'Toy Story (1995)'),
('1', '40', 5.0, 'Toy Story (1995)'),
('1', '43', 5.0, 'Toy Story (1995)'),
('1', '44', 3.0, 'Toy Story (1995)'),
('1', '45', 4.0, 'Toy Story (1995)'),
('1', '46', 5.0, 'Toy Story (1995)'),
('1', '50', 3.0, 'Toy Story (1995)'),
('1', '54', 3.0, 'Toy Story (1995)'),
('1', '57', 5.0, 'Toy Story (1995)')]
I need to calculate the average rating for each film, something like:
[('1', average_ratings_of_film_1, film_name_1),
('2', average_ratings_of_film_2, film_name_2)]
thank you very much for your help
You can use the following to convert your list to a DF and then use groupby().avg()
data = spark.sparkContext.parallelize(
[('1', '1', 4.0, 'Toy Story (1995)'),
('1', '5', 4.0, 'Toy Story (1995)'),
('1', '7', 4.5, 'Toy Story (1995)'),
('1', '15', 2.5, 'Toy Story (1995)'),
('1', '17', 4.5, 'Toy Story (1995)'),
('1', '18', 3.5, 'Toy Story (1995)'),
('1', '19', 4.0, 'Toy Story (1995)'),
('1', '21', 3.5, 'Toy Story (1995)'),
('1', '27', 3.0, 'Toy Story (1995)'),
('1', '31', 5.0, 'Toy Story (1995)'),
('1', '32', 3.0, 'Toy Story (1995)'),
('1', '33', 3.0, 'Toy Story (1995)'),
('1', '40', 5.0, 'Toy Story (1995)'),
('1', '43', 5.0, 'Toy Story (1995)'),
('1', '44', 3.0, 'Toy Story (1995)'),
('1', '45', 4.0, 'Toy Story (1995)'),
('1', '46', 5.0, 'Toy Story (1995)'),
('1', '50', 3.0, 'Toy Story (1995)'),
('1', '54', 3.0, 'Toy Story (1995)'),
('1', '57', 5.0, 'Toy Story (1995)')])
df = data.toDF(schema=["movie_id", "user_id", "rating", "movie"])
group = df.groupby("movie").avg("rating")
group.show()
#+----------------+-----------+
#| movie|avg(rating)|
#+----------------+-----------+
#|Toy Story (1995)| 3.875|
#+----------------+-----------+