dart中的一些使用技巧
公众号:""
华为云享专家,InfoQ签约作者,阿里云专家博主,51CTO博客首席体验官,,专注于大前端技术的分享,包括Flutter,小程序,安卓,VUE,JavaScript。
list - flutter -如何计算列表中的平均数据?
我有一个有关用户食物的List<Comment>
。 看起来像这样:
[
{userId: 1,
rating: 4.5
},
{userId: 2,
rating: 4.0
},
{userId: 3,
rating: 3.5
},
{userId: 4,
rating: 3.0
}
...
];
我想获得平均评分。 AVERAGE = Number of ratings : total user
,如何在dart中应用呢?
最佳答案
var values = [
{'userId': 1, 'rating': 4.5},
{'userId': 2, 'rating': 4.0},
{'userId': 3, 'rating': 3.5},
{'userId': 4, 'rating': 3.0}
];
var result = values.map((m) => m['rating']).reduce((a, b) => a + b) / values.length;
print(result);
dart - 如何从Dart中的列表中找到最小值和最大值?
我已经尝试了以下代码段。但是它将引发有关类型转换的错误。因为列表具有整数和 double 值的组合。但是 list.reduce(min)返回唯一的整数值。因此,您能为这些人提供解决方案吗?提前致谢。 注意-但是,我从用户那里获得了唯一的动态列表。
final List<dynamic> y = [12, 12, 23.5, 2, 19, 1, 23, 16, 29.7, 32, 45, 68, 23, 21];
List<num> yValues = y;
num yMin = yValues.reduce(min);
num yMax = yValues.reduce(max);
最佳答案
您正在编写List的类型为List<dynamic>
。由于min
和max
仅适用于num
类型,因此我们需要将列表中的每个元素cast
转换为num
,如下所示:
import 'dart:math';
void main() {
final List<dynamic> y = <dynamic>[12, 12, 23.5, 2, 19, 1, 23, 16, 29.7, 32, 45, 68, 23, 21];
final yMin = y.cast<num>().reduce(min);
final yMax = y.cast<num>().reduce(max);
print(yMin); // 1
print(yMax); // 68
flutter - 如何在Dart/Flutter中将某些元素从一个Map复制到新Map中?
如何在Dart / Flutter中将某些元素从一个Map复制到新Map中?
Old_Map = {
'A' : {Big : 'A', Small : 'a' },
'B' : {Big : 'B', Small : 'b' },
'C' : {Big : 'C', Small : 'c' },
'D' : {Big : 'D', Small : 'd' },
}
Old_Map => New_Map
我只想要
'B' : {Big : 'B', Small : 'b' },
'C' : {Big : 'C', Small : 'c' },
最佳答案
你可以这样
final oldMap = {
'A': {'Big': 'A', 'Small': 'a'},
'B': {'Big': 'B', 'Small': 'b'},
'C': {'Big': 'C', 'Small': 'c'},
'D': {'Big': 'D', 'Small': 'd'},
};
final newMap =
Map.fromIterable(oldMap.keys.where((k) => k == 'B' || k =='C'),
key: (k) => k, value: (v) => oldMap[v]);
由于keys
返回 map 键的Iterable<String>
,因此您可以使用where
方法检查所需的键,然后可以基于旧 map 值填充值。
stream - Dart 流中的 listen 和 forEach 有什么区别?
如果我有 Stream
在 Dart 中,我可以同时使用 listen
和 forEach
,但我不明白其中的区别。
因此,例如考虑以下代码:
final process = await Process.start('pub', ['serve']);
process.stdout.map((l) => UTF8.decode(l)).forEach(print);
我也可以写:
process.stdout.map((l) => UTF8.decode(l)).listen(print);
有什么区别吗?
最佳答案
forEach
Stream
上的函数将在第一个错误处停止,并且不会给您 StreamSubscription
控制您在流上收听的方式。使用 forEach
如果这是您想要的,那就太好了 - 它会告诉您何时完成(返回的 Future
)并且您所要做的就是处理事件。如果您需要更多控制,可以使用 listen
打电话是怎么回事forEach
被执行。
这就像Iterable.forEach
之间的区别和 Iterable.iterator
- 前者只是为每个元素调用一个回调,另一个给你一种控制迭代的方法。
dart - 如何制作新数组嵌套排序映射?
我有一个看起来像这样的数据块:
var list = [
{ id: '1', title: 'thing1', week: 1, day: 1 },
{ id: '2', title: 'thing2', week: 1, day: 1 },
{ id: '3', title: 'thing3', week: 1, day: 2 },
{ id: '4', title: 'thing4', week: 1, day: 2 },
{ id: '5', title: 'thing5', week: 1, day: 3 },
{ id: '6', title: 'thing6', week: 1, day: 3 },
{ id: '7', title: 'thing7', week: 2, day: 4 },
{ id: '8', title: 'thing8', week: 2, day: 5 },
];
我想要做的是将这个 List 转换为输出这个的东西:
var transformedList = [
{ 'Week 1': [
{ id: '1', title: 'thing1', day: 1, week: 1 },
{ id: '2', title: 'thing2', day: 1, week: 1 },
{ id: '3', title: 'thing3', day: 2, week: 1 },
{ id: '4', title: 'thing4', day: 2, week: 1 },
{ id: '5', title: 'thing5', day: 3, week: 1 },
{ id: '6', title: 'thing6', day: 3, week: 1 },
],
'Week 2': [
{ id: '7', title: 'thing7', day: 4, week: 2 },
{ id: '8', title: 'thing8', day: 5, week: 3 },
]
}
]
到目前为止我尝试过的是:
var programMap = Map.fromIterable(userProgramSteps, key: (k) => k.getWeek(), value: (v) => v);
// handles the week port just fine, but very stuck on the list of days.
我对flutter和 Dart 很陌生,所以我有点迷茫......有人可以帮忙吗?
最佳答案
尊重您之前(已删除)的问题,这里的代码: data_weeks.dart
const week_data = [
{ 'id': '1', 'week': 1, 'day': 1, 'title': 'thing1' },
{ 'id': '2', 'week': 1, 'day': 1, 'title': 'thing2' },
{ 'id': '3', 'week': 1, 'day': 1, 'title': 'thing3' },
{ 'id': '4', 'week': 1, 'day': 2, 'title': 'thing4' },
{ 'id': '5', 'week': 1, 'day': 2, 'title': 'thing5' },
{ 'id': '6', 'week': 2, 'day': 3, 'title': 'thing6' },
{ 'id': '7', 'week': 2, 'day': 4, 'title': 'thing7' },
];
home_page.dart
import 'package:flutter/material.dart';
import 'package:list_cards/src/shared/data_weeks.dart';
class HomePage extends StatelessWidget {
/* ---------------------------------------------------------------------------- */
const HomePage({Key key}) : super(key: key);
/* ---------------------------------------------------------------------------- */
@override
Widget build(BuildContext context) {
final data = getNewData();
return Scaffold(
appBar: AppBar(
title: Text('Hi!'),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) => ListTile(
title: Text(
'Week ${data.keys.toList()[index]}',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
subtitle: getSubtitles1(data[data.keys.toList()[index]], context),
),
),
),
);
}
Widget getSubtitles1(List<Map<int, Object>> data, BuildContext context) {
return Column(
children: List.generate(data.length, (index) => ListTile(
title: Text(
'DAY ${data[index].keys.toList()[0]}',
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black.withOpacity(0.4)
),
),
subtitle: getSubtitles2(data[index][data[index].keys.toList()[0]], context),
)),
);
}
Widget getSubtitles2(List<String> data, BuildContext context) {
final size = MediaQuery.of(context).size;
return Column(
children: List.generate(data.length, (index) => Card(
elevation: 0,
margin: EdgeInsets.all(0),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
child: Row(
children: [
Container(
width: (size.width + 80) / 2,
child: Text(data[index]),
),
IconButton(icon: Icon(Icons.check_box_outline_blank), onPressed: () {}),
],
),
),
)),
);
}
Map<int, Object> getNewData() {
var weeks = week_data.map<int>((m) => m['week']).toSet().toList();
var newData = Map<int, Object>();
weeks.forEach((w) {
newData[w] = week_data.where((m) => m['week'] == w).map<int>((m) => m['day']).toSet().map<Map<int, Object>>((e) => {e: week_data.where((m) => m['week'] == w && m['day'] == e).map<String>((m) => m['title']).toList()}).toList();
});
return newData;
}
}
结果: 关于您当前的问题,getNewData()
方法包含您的答案的逻辑。好好享受!
dart - Flutter:删除所有已保存的shared_preferences首选项
想在用户点击注销时删除所有保存的shared_preferences首选项。有什么方法可以一次性完成而不删除一个吗?
最佳答案
我使用shared_preferences
插件: 用pubspec.yaml
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.4.3
并在dart文件中:
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
...
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.clear();
我觉得这就是你所需要的
- 点赞
- 收藏
- 关注作者
评论(0)