Created
October 8, 2022 13:40
-
-
Save wickstjo/72b7c0ef92ebaa6a7eca04c59452aab3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_riverpod/flutter_riverpod.dart'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
main() async { | |
runApp(const MaterialApp( | |
home: Scaffold(body: Component()) | |
)); | |
} | |
class Component extends ConsumerStatefulWidget { | |
const Component({ Key? key }): super(key: key); | |
@override MainBody createState() => MainBody(); | |
} | |
class MainBody extends ConsumerState<Component> { | |
late int current_count = 0; | |
Future<List<String>> get_storage() async { | |
final prefs = await SharedPreferences.getInstance(); | |
List<String> container = []; | |
if (prefs.containsKey('data')) { | |
container = prefs.getStringList('data')!; | |
} | |
return container; | |
// return ['1', '2', '3']; | |
} | |
void update_storage(List<String> old_data) async { | |
final prefs = await SharedPreferences.getInstance(); | |
final next_value = (old_data.length + 1).toString(); | |
old_data.add(next_value); | |
prefs.setStringList('data', old_data); | |
setState(() { | |
current_count = current_count + 1; | |
}); | |
} | |
@override Widget build(BuildContext context) { | |
return FutureBuilder<List>( | |
future: get_storage(), | |
builder: (BuildContext context, AsyncSnapshot snapshot) { | |
// RENDER NORMAL CONTENT | |
if (snapshot.hasData) { | |
List<String> response = snapshot.data!; | |
return Column(children: [ | |
ElevatedButton( | |
onPressed: () => update_storage(response), | |
child: Text('Items: ${response.length}') | |
), | |
response.length > 0 ? Column( | |
children: response.map((item) => Text(item)).toList() | |
) : Container() | |
]); | |
// RENDER ENCOUNTERED ERROR | |
} else if (snapshot.hasError) { | |
return Text('${snapshot.error}'); | |
} | |
// OTHERWISE, RENDER LOADING SCREEN | |
return const CircularProgressIndicator(); | |
}, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment