Skip to content

Instantly share code, notes, and snippets.

@DaisukeNagata
Created April 25, 2023 06:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Easy way to reload
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('ListView Sample'),
),
body: const RefreshList(),
),
);
}
}
class RefreshList extends StatefulWidget {
const RefreshList({super.key});
@override
State<RefreshList> createState() => _RefreshListState();
}
class _RefreshListState extends State<RefreshList> with ChangeNotifier {
List<String> items = List.generate(30, (index) => "Item ${index + 1}");
void shuffleList() {
items.shuffle(Random()); // <- setStateを指定しない。利用したい箇所はnotify()methodでリロード
notify();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: shuffleList,
child: const Text('Reload Data'),
),
),
],
);
}
void notify() {
setState(() {
notifyListeners();
});
}
}
@DaisukeNagata
Copy link
Author

default.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment