Skip to content

Instantly share code, notes, and snippets.

@DaisukeNagata
Created April 25, 2023 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaisukeNagata/335afb8c5604dacf2186acf5056dc362 to your computer and use it in GitHub Desktop.
Save DaisukeNagata/335afb8c5604dacf2186acf5056dc362 to your computer and use it in GitHub Desktop.
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