Skip to content

Instantly share code, notes, and snippets.

@AnthonyDS
Last active January 26, 2023 06:34
Show Gist options
  • Save AnthonyDS/212fea84aeb90a7ee49d1e7f5ac849e0 to your computer and use it in GitHub Desktop.
Save AnthonyDS/212fea84aeb90a7ee49d1e7f5ac849e0 to your computer and use it in GitHub Desktop.
Flutter Provider
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
typedef Json = Map<String, dynamic>;
class User {
final int id;
final String firstName;
final String lastName;
final String avatar;
const User({
required this.id,
required this.firstName,
required this.lastName,
required this.avatar,
});
}
Future<User?> _getFutureData() async {
await Future.delayed(const Duration(seconds: 3), () {});
var response = await http.get(Uri.parse('https://reqres.in/api/users/2'));
if (response.statusCode == 200 && response.body.isNotEmpty) {
Json json = jsonDecode(response.body);
return User(
id: json['data']['id'],
firstName: json['data']['first_name'],
lastName: json['data']['last_name'],
avatar: json['data']['avatar'],
);
}
return null;
}
class StreamUser {
final int id;
final String name;
const StreamUser({
required this.id,
required this.name,
});
}
int streamUserId = 0;
Stream<StreamUser?> _getStreamData() {
return Stream<StreamUser?>.periodic(
const Duration(seconds: 1),
(x) {
streamUserId++;
return StreamUser(id: streamUserId, name: 'StreamUser');
},
);
}
void main() {
runApp(
// ChangeNotifierProvider(
// create: (context) => CounterState(),
// child: const CounterApp(),
// ),
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => CounterState()),
ProxyProvider<CounterState, ColorState>(
update: (_, counter, __) => ColorState(counter.count),
),
FutureProvider<User?>(
initialData: null,
create: (context) => _getFutureData(),
),
StreamProvider<StreamUser?>(
initialData: null,
create: (context) => _getStreamData(),
),
],
child: const CounterApp(),
),
);
}
class CounterState with ChangeNotifier {
int _count = 0;
int get count => _count;
void incrementCount() {
_count++;
notifyListeners();
// Future.delayed(const Duration(seconds: 2), () {
// _count++;
// notifyListeners();
// });
}
void decrementCount() {
_count--;
notifyListeners();
// Future.delayed(const Duration(seconds: 2), () {
// _count--;
// notifyListeners();
// });
}
}
class ColorState {
final int _color;
ColorState(this._color);
final List<String> colorNames = <String>[
'Красный',
'Оранжевый',
'Жёлтый',
'Зелёный',
'Голубой',
'Синий',
'Фиолетовый',
];
bool _isValidColor() {
return _color >= 0 && _color < colorNames.length;
}
String get colorName =>
_isValidColor() ? colorNames[_color] : 'Какой-то цвет';
}
class CounterApp extends StatelessWidget {
const CounterApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
CountText(),
ColorText(),
SizedBox(height: 8),
CountButtons(),
SizedBox(height: 8),
FutureUser(),
SizedBox(height: 8),
StreamUserText(),
],
),
),
floatingActionButton: const FloatingActionButtonsWidget(),
),
);
}
}
class FloatingActionButtonsWidget extends StatelessWidget {
const FloatingActionButtonsWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
key: const Key('floatingActionButton_increment'),
child: const Icon(Icons.add),
onPressed: () => context.read<CounterState>().incrementCount(),
),
const SizedBox(height: 16),
FloatingActionButton(
key: const Key('floatingActionButton_decrement'),
child: const Icon(Icons.remove),
onPressed: () => context.read<CounterState>().decrementCount(),
),
],
);
}
}
class CountText extends StatelessWidget {
const CountText({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final state = context.watch<CounterState>();
// final state2 = Provider.of<CounterState>(context);
return Text('${state.count}', style: const TextStyle(fontSize: 70));
}
}
class ColorText extends StatelessWidget {
const ColorText({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final state = context.watch<ColorState>();
// final state2 = Provider.of<ColorState>(context);
return Text(state.colorName, style: const TextStyle(fontSize: 24));
}
}
class CountButtons extends StatelessWidget {
const CountButtons({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: const Text('Увеличить'),
onPressed: () => context.read<CounterState>().incrementCount(),
// onPressed: () => Provider.of<CounterState>(context, listen: false).incrementCount(),
),
const SizedBox(width: 20),
ElevatedButton(
child: const Text('Уменьшить'),
onPressed: () => context.read<CounterState>().decrementCount(),
// onPressed: () => Provider.of<CounterState>(context, listen: false).decrementCount(),
),
],
);
}
}
class FutureUser extends StatelessWidget {
const FutureUser({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final User? user = context.watch<User?>();
return user == null
? const Text('Кто ты?', style: TextStyle(fontSize: 24))
: Center(
child: ListTile(
leading: Image.network(user.avatar),
title: Text(
'${user.firstName} ${user.lastName}',
style: const TextStyle(fontSize: 24),
),
subtitle: Text('#${user.id}'),
),
);
}
}
class StreamUserText extends StatelessWidget {
const StreamUserText({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final StreamUser? streamUser = context.watch<StreamUser?>();
return streamUser == null
? const Text('Кто ты?', style: TextStyle(fontSize: 24))
: Text('${streamUser.name}: ${streamUser.id}');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment