Skip to content

Instantly share code, notes, and snippets.

@djad442
Created November 29, 2020 12:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djad442/54a9a6fe4a489ca49045f3f868e92a42 to your computer and use it in GitHub Desktop.
Save djad442/54a9a6fe4a489ca49045f3f868e92a42 to your computer and use it in GitHub Desktop.
use of state mixin in getx
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 CityModel {
CityModel({
this.abbreviation,
this.name,
});
String abbreviation;
String name;
factory CityModel.fromJson(Map<String, dynamic> json) => CityModel(
abbreviation: json["sigla"],
name: json["nome"],
);
static List<CityModel> listFromJson(list) =>
List<CityModel>.from(list.map((x) => CityModel.fromJson(x)));
}
class CityController extends GetxController with StateMixin<List<CityModel>> {
final Dio dio;
CityController({this.dio});
@override
void onInit() {
findAllCities();
super.onInit();
}
findAllCities() {
const String url = 'https://servicodados.ibge.gov.br/api/v1/localidades/estados';
dio.get(url).then((result) {
List<CityModel> data = CityModel.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].name);
},
),
onLoading: Center(child: CircularProgressIndicator()), // optional
onError: (error) => Center( // optional
child: Text('Error: $error',
style: TextStyle(fontSize: 18),
textAlign: TextAlign.center,
),
),
),
),
);
}
}
@BrianMwas
Copy link

As at this moment controller.obx is null why is this so?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment