I am trying to use this package load more in fllutter but the example doesn't work - flutter

I am trying this example, but nothing is shown on the screen of the emulator, any help?? this example is in flutter packages but it doesn't work
Hello, I am trying this example, but nothing is shown on the screen of the emulator, any help?? this example is in flutter packages but it doesn't work
`
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int get count => list.length;
List<int> list = [];
void initState() {
super.initState();
// list.addAll(List.generate(30, (v) => v));
}
void load() {
print("load");
setState(() {
list.addAll(List.generate(15, (v) => v));
print("data count = ${list.length}");
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Container(
child: RefreshIndicator(
child: LoadMore(
isFinish: count >= 60,
onLoadMore: _loadMore,
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Container(
child: Text(list[index].toString()),
height: 40.0,
alignment: Alignment.center,
);
},
itemCount: count,
),
whenEmptyLoad: false,
delegate: DefaultLoadMoreDelegate(),
textBuilder: DefaultLoadMoreTextBuilder.chinese,
),
onRefresh: _refresh,
),
),
);
}
Future<bool> _loadMore() async {
print("onLoadMore");
await Future.delayed(Duration(seconds: 0, milliseconds: 2000));
load();
return true;
}
Future<void> _refresh() async {
await Future.delayed(Duration(seconds: 0, milliseconds: 2000));
list.clear();
load();
}
}
`
Hello, I am trying this example, but nothing is shown on the screen of the emulator, any help??

Related

Flutter Slot Machine Game

I am trying to run flutter slot machine game.
This is from the package and it has three stop buttons to stop the animation.
The issue that I am having is I only want one start button. After delayed 5 secs, I want that to stop that animation without pressing any buttons.
That's what I am trying to do and couldn't figure it out.
Can someone pls help me?
This is the original flutter slot machine game package.
https://pub.dev/packages/flutter_slot_machine/example
You can create async method with Future.delay
onPressed: () async {
onStart();
await Future.delayed(Duration(seconds: 1));
onButtonTap(index: 0);
onButtonTap(index: 1);
onButtonTap(index: 2);
}),
More about async-await
Full widget
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late SlotMachineController _controller;
#override
void initState() {
super.initState();
}
void onButtonTap({required int index}) {
_controller.stop(reelIndex: index);
}
void onStart() {
final index = Random().nextInt(20);
_controller.start(hitRollItemIndex: index < 5 ? index : null);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SlotMachine(
rollItems: [
RollItem(index: 0, child: Text("X")),
RollItem(index: 1, child: Text("Y")),
RollItem(index: 2, child: Text("Z")),
],
onCreated: (controller) {
_controller = controller;
},
onFinished: (resultIndexes) {
print('Result: $resultIndexes');
},
),
Padding(
padding: const EdgeInsets.only(top: 24),
child: TextButton(
child: Text('START'),
onPressed: () async {
onStart();
await Future.delayed(Duration(seconds: 1));
onButtonTap(index: 0);
onButtonTap(index: 1);
onButtonTap(index: 2);
}),
),
],
),
),
);
}
}

shared_preferences Flutter Add items

I expect that when I click the button I will add a single item that has brand and date in it in the Save Data function however I have no idea how to do that.Currently after each click they add tems however they are multiplied by themselves and that completely misses the point . I tried to add a single item however I get information about unsupported Error . In conclusion Please help
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'SharedPreferences Demo',
home: Test(),
);
}
}
class Test extends StatefulWidget {
const Test({Key? key}) : super(key: key);
#override
State<Test> createState() => _TestState();
}
class _TestState extends State<Test> {
List<Map<String, dynamic>> listItems = [];
List<String> cart = [];
final Map<String, dynamic> item = Map<String, String>();
saveData() async {
var date = DateTime.now();
print('save data ');
final Map<String, dynamic> item = Map<String, dynamic>();
item['brand'] = 'item';
item['date'] = 'date';
SharedPreferences prefs = await SharedPreferences.getInstance();
if (cart == null) cart = [];
setState(() {
cart = prefs.getStringList("cart") ?? [];
cart.add(jsonEncode(item));
listItems.add(jsonDecode(item));
//<-- when i click button i want add one item card. on but idk how
prefs.setStringList("cart", cart);
});
}
getUser() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var cart = prefs.getStringList("cart");
setState(() {
if (cart == null) {
print('null');
} else {
cart.forEach((item) {
listItems.add(jsonDecode(item));
});
}
});
}
#override
void initState() {
super.initState();
getUser();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(
child: listItems.isNotEmpty
? ListView.builder(
itemCount: listItems.length, itemBuilder: buildList)
: Center(
child: Text('EMPTY LIST'),
)),
Center(
child: FloatingActionButton(
onPressed: saveData,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
)
],
),
);
}
Widget buildList(BuildContext context, int index) {
return Container(
margin: EdgeInsets.all(4),
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
width: 2,
),
borderRadius: BorderRadius.circular(5)),
child: ListTile(
title: Text(listItems[index]['brand']),
subtitle: Text(listItems[index]['date'] ?? "null"),
),
);
}
}
}

Flutter - How to connect void to build widget?

I am trying to get a new historyTile() to be called to the Scaffold() each second. I am unsure how to make the void function connect.
Any advice and feedback is appreciated!
Code:
class activityTab extends StatefulWidget {
const activityTab({Key? key}) : super(key: key);
#override
State<activityTab> createState() => _activityTabState();
}
class _activityTabState extends State<activityTab> {
#override
void historyTile() {
final now = DateTime.now();
String tileTime = DateFormat.yMMMMd().add_jm().format(now);
ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.backup_outlined),
title: Text('Synced my_script.pdf with the cloud.'),
subtitle: Text('${tileTime}'),
tileColor: Colors.greenAccent,
);
}
);
}
#override
void initState() {
super.initState();
Timer.periodic(Duration(seconds: 1), (Timer t) => historyTile());
}
#override
Widget build(BuildContext context) {
return Scaffold(
body:
Container(
child: SingleChildScrollView(
child: historyTile(); // ERROR HERE
),
),
);
}
}
You can try creating periodic streams with a Stream Builder widget. If not, the simplest method is to put your widget in scaffold and try calling the setState function periodically with a 1-second timer.
In the StreamBuilder example you should change the widget a bit. Sending the parameter you want to update to the widget from outside will add a little more flexibility to you.
return Scaffold(
body: StreamBuilder<String>(
stream: Stream.periodic(const Duration(seconds: 1), (x) {
// Your Action Here
final now = DateTime.now();
return DateFormat.yMMMMd().add_jm().format(now);
}),
builder: (context, snapshot) {
String param = "";
if (snapshot.hasData) param = snapshot.data!;
return _historyTile(txt = param);
}
),
);
Or you could use your widget in Scaffold Body and periodically set the widgets state in timer callback.
class _activityTabState extends State<activityTab> {
String tileTime = "";
...
Timer.periodic(Duration(seconds: 1), () {
setState(() {
final now = DateTime.now();
tileTime = DateFormat.yMMMMd().add_jm().format(now);
});
};
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: SingleChildScrollView(
child: historyTile(tileName);
),
),
);
}
or just
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: SingleChildScrollView(
child: ListTile(
leading: Icon(Icons.backup_outlined),
title: Text('Synced my_script.pdf with the cloud.'),
subtitle: Text('$tileTime'),
tileColor: Colors.greenAccent,
),
),
),
);
}
Create your historyTile widget as a custom widget
class HistoryTile extends StatefulWidget {
const HistoryTile({Key? key, required this.txt}) : super(key: key);
final String txt;
#override
State<HistoryTile> createState() => _HistoryTileState();
}
class _HistoryTileState extends State<HistoryTile> {
#override
Widget build(BuildContext context) {
return ListTile(
leading: Icon(Icons.backup_outlined),
title: Text('Synced my_script.pdf with the cloud.'),
subtitle: Text(widget.txt),
tileColor: Colors.greenAccent,
);
}
}
there is some issues in you ListView.Builder. You do not put itemCount there. And you need to use setState in timer. So codes are below. Please check.
class activityTab extends StatefulWidget {
const activityTab({Key? key}) : super(key: key);
#override
State<activityTab> createState() => _activityTabState();
}
class _activityTabState extends State<activityTab> {
String _now;
Timer _everySecond;
#override
historyTile() {
final now = DateTime.now();
String tileTime = DateFormat.yMMMMd().add_jms().format(now);
return ListView.builder(
shrinkWrap: true,
itemCount: 1,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.backup_outlined),
title: Text('Synced my_script.pdf with the cloud.'),
subtitle: Text('${tileTime}'),
tileColor: Colors.greenAccent,
);
});
}
void _timer() {
Future.delayed(Duration(seconds: 1)).then((_) {
setState(() {
_timer();
});
});
}
#override
void initState() {
super.initState();
_timer();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: 500,
child: SingleChildScrollView(
child: historyTile(),
),
),
);
}
}

When I add elements to listview, how to update listview in Flutter?

I am new to flutter and I would like to add element every 5 seconds to my list view. I have list view and I think I have the true adding method. However, I do not know how to update my list view every 5 seconds.
void randomCity(){
List <int> colors = [yellow,green,blue,red,black,white];
List <String> countryNames = ["Gdańsk","Warszawa","Poznań","Białystok","Wrocław","Katowice","Kraków"];
List <String> countryImages = [gdanskPic,warszawaPic,poznanPic,bialystokPic,wroclawPic,katowicePic,krakowPic];
Random random = new Random();
DateTime now = new DateTime.now();
Future.delayed(Duration(seconds: 5), (){
setState(() {
int randomCity = random.nextInt(countryNames.length);
int randomColor = random.nextInt(colors.length);
countrylist.add(Country(
countryNames[randomCity], countryImages[randomCity],
colors[randomColor], now.toString()));
});
});
}
In this code I am adding new element to my list view.
randomCity();
return Scaffold(
backgroundColor: Colors.grey[100],
appBar: AppBar(
backgroundColor: Colors.grey[100],
elevation: 0.0,
title: Text(
"Random City App",
style: TextStyle(fontSize: 20.0, color: Colors.black),
),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.add,
color: Colors.black,
size: 32,
),
onPressed: () {})
],
),
body: ListView.builder(
itemCount: countrylist.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => CountryDetails(countryName: countrylist[index].name,
appBarColor: countrylist[index].color, date: countrylist[index].date, image: countrylist[index].image,))
);
},
title: Text(countrylist[index].name + " ${countrylist[index].date}"),
tileColor: Color(countrylist[index].color),
),
);
},
));
}
And this is my ListView.Builder.
You have to convert your widget into StatefulWidget and then rebuild it with setState (more info on ways to manage state https://flutter.dev/docs/development/data-and-backend/state-mgmt/options)
class MyApp extends StatelessWidget { // your main widget
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: MyWidget(),
),
);
}
}
class MyWidget extends StatefulWidget { // create new StatefulWidget widget
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
List<Country> countrylist = []; // mover other variables in here
...
void randomCity(){
...
setState(() {}); // this will rebuild your widget again and again
}
#override
Widget build(BuildContext context) {
Future.delayed(Duration(seconds: 5), (){
randomCity();
});
return ListView.builder(
itemCount: countrylist.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
onTap: () {},
title: Text(countrylist[index]),
),
);
},
);
}
}
You have to tell the ListView to rebuild which you can do with the setState method (if you are using a StefulWidget). Also, I would use Timer instead of Future.delayed for periodic updates. Here would be a simplified example of your usecase:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Timer timer;
final countryNames = ['Germany', 'Croatia', 'Turkey', 'USA'];
List<String> countryList = [];
#override
void initState() {
Timer.periodic(Duration(seconds: 5), (timer) {
int randomCity = Random().nextInt(countryNames.length);
countryList.add(countryNames[randomCity]);
setState(() {});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List Updater'),
),
body: ListView.builder(
itemBuilder: (context, index) {
return Card(
child: Text(countryList[index]),
);
},
itemCount: countryList.length,
),
);
}
#override
void dispose() {
timer?.cancel();
super.dispose();
}
}

Using jumpto and sticky_headers package causes UI issue

I created a new flutter project and added the sticky_headers package.
Afterwards I implemented a list builder that has a ScrollController.
I call setState 3 times at a 5 seconds interval and modify a global offset variable which will be used on the build method to jump the list to a new offset (using SchedulerBinding.instance.addPostFrameCallback).
The problem is that after I call the jumpto method, the headers are messed up ( if I manual scroll the headers will come back to a normal position).
Example:
The code:
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:sticky_headers/sticky_headers.dart';
double offset = 0;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
ScrollController _scrollController = ScrollController();
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 5)).then((_) => setState(() {
offset = 3000;
})).then((_) async => await Future.delayed(Duration(seconds: 5))).then((_) => setState(() {
offset = 1000;
})).then((_) async => await Future.delayed(Duration(seconds: 5))).then((_) => setState(() {
offset = 5000;
}));
}
#override
Widget build(BuildContext context) {
SchedulerBinding.instance.addPostFrameCallback((_) {
print(offset);
_scrollController.jumpTo(offset);
});
return Scaffold(body: Container(padding: EdgeInsets.only(top: 20),child: _buildList(context)));
}
Widget _buildList(BuildContext context) {
return NotificationListener<ScrollNotification>(
child: ListView.builder(
controller: _scrollController,
itemCount: 100,
itemBuilder: (BuildContext context, int sectionIndex) => StickyHeader(
header: Container(
height: 50,
alignment: Alignment.center,
color: Colors.blue,
child: Text("$sectionIndex")),
content: ListView.builder(
itemCount: 10,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, rowIndex) => Container(
color: Colors.white,
child: Text("$sectionIndex"))))),
onNotification: (ScrollNotification scrollNotification) {
offset = _scrollController.offset;
print(offset);
return true;
});
}
}