Skip to content

Instantly share code, notes, and snippets.

@eduardoflorence
Created October 27, 2020 18:09
Show Gist options
  • Save eduardoflorence/8b5a0b5139aadb4c31ddde1d28da9323 to your computer and use it in GitHub Desktop.
Save eduardoflorence/8b5a0b5139aadb4c31ddde1d28da9323 to your computer and use it in GitHub Desktop.
GetX - Sample StateMixin
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart';
void main() {
runApp(GetMaterialApp(
initialRoute: '/home',
getPages: [
GetPage(
name: '/home',
page: () => HomePage(),
),
GetPage(
name: '/city',
page: () => CityPage(),
binding: CityBinding(),
),
],
));
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('HOME')),
body: Center(
child: RaisedButton(
onPressed: () => Get.toNamed('/city'),
child: Text('Go to Cities'),
),
),
);
}
}
class CityBinding extends Bindings {
@override
void dependencies() {
Get.put(Dio());
Get.put(CityController(dio: Get.find()));
}
}
class StateModel {
StateModel({
this.sigla,
this.nome,
});
String sigla;
String nome;
factory StateModel.fromJson(Map<String, dynamic> json) => StateModel(
sigla: json["sigla"],
nome: json["nome"],
);
Map<String, dynamic> toJson() => {
"sigla": sigla,
"nome": nome,
};
static List<StateModel> listFromJson(list) =>
List<StateModel>.from(list.map((x) => StateModel.fromJson(x)));
}
class CityController extends GetxController with StateMixin<List<StateModel>> {
final Dio dio;
CityController({this.dio});
@override
void onInit() {
super.onInit();
const String url =
'https://servicodados.ibge.gov.br/api/v1/localidades/estados';
dio.get(url).then((result) {
List<StateModel> data = StateModel.listFromJson(result.data);
change(data, status: RxStatus.success());
}, onError: (err) {
change(null, status: RxStatus.error(err.toString()));
});
}
}
class CityPage extends GetView<CityController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Cities')),
body: Container(
child: controller.obx(
(state) => ListView.builder(
itemCount: state.length,
itemBuilder: (context, index) {
return Text(state[index].nome);
},
),
onLoading: Center(child: CircularProgressIndicator()),
onError: Center(
child: Text(
'Erro ao consultar os Estados do Brasil',
style: TextStyle(fontSize: 18),
textAlign: TextAlign.center,
),
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment