显示列表中的随机 10 个元素颤动 [关闭]
Posted
技术标签:
【中文标题】显示列表中的随机 10 个元素颤动 [关闭]【英文标题】:Displaying random 10 elements from a list flutter [closed] 【发布时间】:2020-09-20 08:09:33 【问题描述】:我有一个从 rest Api 中获取的列表并按上述方式存储。
然后在我的列表视图中。我在列表中显示所有项目的构建器,但我想一次显示 10 个项目,它们应该是随机的,这样每当我刷新我的页面时,我都会显示一个新的项目列表。我不想在列表中显示只是因为我希望用户单击查看全部按钮以在不同页面中查看列表中的所有项目。我的问题是我该如何去做,因为我设法做的是显示仅随机一项,并使其随机
【问题讨论】:
【参考方案1】:请检查以下示例。您可以在此处将 API 的响应分配给data
。
import 'dart:math';
import 'package:flutter/material.dart';
void main()
runApp(MyApp());
class MyApp extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: Color.fromARGB(255, 18, 32, 47)),
debugShowCheckedModeBanner: false,
home: HomePage(),
);
class HomePage extends StatefulWidget
@override
_HomePageState createState() => _HomePageState();
class _HomePageState extends State<HomePage>
final _random = new Random();
var data = [
'T 0',
'T 1',
'T 2',
'T 3',
'T 4',
'T 5',
'T 6',
'T 7',
'T 8',
'T 9',
'T 10',
'T 11',
'T 12',
'T 13',
'T 14',
'T 15',
'T 16',
'T 17',
'T 18',
'T 19',
];
var listToShow = [];
@override
Widget build(BuildContext context)
return Scaffold(
bottomNavigationBar: BottomAppBar(
shape: CircularNotchedRectangle(),
child: Container(
height: 75,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
iconSize: 30.0,
padding: EdgeInsets.only(left: 28.0),
icon: Icon(Icons.refresh),
onPressed: ()
setState(()
updateDataInList();
);
,
),
IconButton(
iconSize: 30.0,
padding: EdgeInsets.only(right: 28.0),
icon: Icon(Icons.all_inclusive),
onPressed: ()
setState(()
showAllData();
);
,
),
],
),
),
),
body: ListView.builder(
itemCount: listToShow.length,
itemBuilder: (context, i)
return Ink(
color: Colors.blueGrey,
child: ListTile(
title: Text(listToShow[i].toString()),
),
);
,
),
);
void updateDataInList()
listToShow = new List.generate(10, (_) => data[_random.nextInt(data.length)]);
void showAllData()
listToShow = data;
【讨论】:
代码运行良好,但存在问题,因为某些记录会自我复制 您可以创建自定义方法来生成随机数。检查thislistToShow = new List.generate(2, (_) => data[_random.nextInt(data.length)]).toSet().toList();
以上是关于显示列表中的随机 10 个元素颤动 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
查找“随机”字符串列表中至少 2 个元素上存在的最长前缀 [关闭]