Last active
October 13, 2021 21:09
-
-
Save IsmailAlamKhan/cfc86aef4de62a89764f1dade8f1b82e to your computer and use it in GitHub Desktop.
This file contains hidden or 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'; | |
final provider = StateNotifierProvider<SomeProvider, String>( | |
(_) => throw UnimplementedError()); | |
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: 'Material App', home: Home()); | |
} | |
} | |
class Home extends StatefulWidget { | |
const Home({ | |
Key? key, | |
}) : super(key: key); | |
@override | |
State<Home> createState() => _HomeState(); | |
} | |
class _HomeState extends State<Home> { | |
/// Your api call | |
final _future = | |
Future<String>.delayed(const Duration(seconds: 3), () => 'Data arrived'); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: const Text('Material App Bar')), | |
body: Center( | |
child: FutureBuilder<String>( | |
future: _future, | |
builder: (context, snapshot) { | |
if (snapshot.connectionState == ConnectionState.done) { | |
return ProviderScope( | |
overrides: [ | |
provider.overrideWithValue(SomeProvider(snapshot.data!)) | |
], | |
child: const SomeWidget(), | |
); | |
} else { | |
return const CircularProgressIndicator(); | |
} | |
}, | |
), | |
), | |
); | |
} | |
} | |
class SomeWidget extends ConsumerWidget { | |
const SomeWidget({ | |
Key? key, | |
}) : super(key: key); | |
@override | |
Widget build(BuildContext context, ScopedReader watch) { | |
return Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Text(watch(provider)), | |
const SizedBox(height: 10), | |
ElevatedButton( | |
child: const Text('Change'), | |
onPressed: context.read(provider.notifier).changeDataToSomething, | |
), | |
], | |
); | |
} | |
} | |
class SomeProvider extends StateNotifier<String> { | |
final String somedataFromApi; | |
SomeProvider(this.somedataFromApi) : super(somedataFromApi); | |
void changeDataToSomething() { | |
state = 'Data changed'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment